#python #pandas #dataframe #openpyxl
#python #pandas #фрейм данных #openpyxl
Вопрос:
Вот мой код python, который не работает:
import os, fnmatch
from openpyxl import Workbook as wb
import openpyxl as opxl
import pandas as pd
def read_excel_sheets(xls_path):
"""Read all sheets of an Excel workbook and return a single DataFrame (or in my case dictionary)"""
print(f'Loading {xls_path} into pandas')
xl = pd.ExcelFile(xls_path)
df = pd.DataFrame()
columns = None
for idx, shtnm in enumerate(xl.sheet_names):
print(f'Reading sheet #{idx}: {shtnm}')
sheet = xl.parse(shtnm)
print("You are seeing the function read_excel_sheets executing.The current sheet name is:n",shtnm,"n",type(shtnm))
print("You are seeing the function read_excel_sheets executing.n",sheet,"n",type(sheet))
if shtnm == 'Cover Page':
myloc=sheet[1].str.contains('Location').any() #this line does not work
print("first column of sheetn",sheet[1])
return True
У меня есть код, который входит в конкретную электронную таблицу с именем «Титульная страница», но ни одна из функций поиска, похоже, не работает (или, по крайней мере, возвращает желаемые результаты). Я продолжаю получать эту ошибку для указанной строки. Возвращаемое значение имеет значение True, чтобы здесь было действительно просто. Я пробовал find(), findall(), contains(), search(), но все они, похоже, связаны с серией pandas (или работают с ней) и не обязательно с фреймами данных.
return self._engine.get_loc(key)
File "pandas/_libs/index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "read_all_folders_files.py", line 66, in <module>
xlparseop=read_excel_sheets(filename)
File "read_all_folders_files.py", line 39, in read_excel_sheets
print("first column of sheetn",sheet[1])
File "/Users//anaconda3/lib/python3.8/site-packages/pandas/core/frame.py", line 2800, in __getitem__
indexer = self.columns.get_loc(key)
File "/Users//anaconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 2648, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas/_libs/index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 1
Комментарии:
1. Ваша ключевая
sheet[1]
ошибка, скорее всего, возникает, когда вы объявляетеparse()
pandas returns: parsed: DataFrame или Dict of DataFrames DataFrame из переданного в файле Excel. См. Примечания в аргументе sheetname для получения дополнительной информации о том, когда возвращается Dict фреймов данных .. .. В этом случае вы, вероятно, вызываете 1 в качестве ключа объекта, подобного словарю… распечатайтеtype(sheet)
, чтобы увидеть, а также убедитесь, что у вас есть это значение в объекте, который вы пытаетесь собрать2. sheet — это фрейм данных pandas.
3. да, значит, ваша ошибка возникает
sheet[1]
из-за того, что она недействительна, потому что ключ1
недействителен. Вот почему вы получаетеKeyError: 1
. Определите действительный ключ, который вам нужен, и все готово. Попробуйтеprint(sheet.__dict__)
, и вы должны увидеть атрибуты.