首页 > 解决方案 > Pandas 数据框返回所有搜索功能的关键错误

问题描述

这是我的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 sheet\n",sheet[1])  
    return True

我确实将代码放入名为“封面页”的特定电子表格中,但所有搜索功能似乎都没有工作(或至少返回所需的结果)。对于指出的行,我不断收到此错误。返回值设置为 True 以保持此处非常简单。我试过 find(),findall(), contains(), search() 但它们似乎都与(或使用)熊猫系列有关,不一定与数据框有关。

    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 sheet\n",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

标签: pythonpandasdataframeopenpyxl

解决方案


推荐阅读