Skip to main content
 首页 » 编程设计

python之从 Excel 数据读入数据框时出现 KeyError

2025年05月04日13qlqwjy

我有一个包含两张工作表的 Excel 文件,我正在尝试将它们都读入数据框中,如下面的代码所示。但是,我得到了错误

KeyError: "['months_to_maturity' 'asset_id' 'orig_iss_dt' 'maturity_dt' 'pay_freq_cd'\n 'coupon' 'closing_price'] not in index" 

在行中

return df[['months_to_maturity', 'asset_id', 'orig_iss_dt', 'maturity_dt' , 'pay_freq_cd', 'coupon', 'closing_price']] 

在 SecondExcelFileReader() 函数中。但是,两张纸都有标题

asset_id    orig_iss_dt maturity_dt  pay_freq_cd    coupon  closing_price   months_to_maturity 

我按如下方式返回 df,因为这是我想要的列的顺序。

def ExcelFileReader(): 
    xls = pd.ExcelFile('D:/USDataRECENTLY.xls') 
    df = xls.parse(xls.sheet_names[0]) 
    return df[['months_to_maturity', 'asset_id', 'orig_iss_dt', 'maturity_dt' , 'pay_freq_cd', 'coupon', 'closing_price']] 
 
 
def SecondExcelFileReader(): 
    xls = pd.ExcelFile('D:/USDataRECENTLY.xls') 
    df = xls.parse(xls.sheet_names[1]) 
    return df[['months_to_maturity', 'asset_id', 'orig_iss_dt', 'maturity_dt' , 'pay_freq_cd', 'coupon', 'closing_price']] 
 
def mergingdataframes(): 
    df1 = ExcelFileReader() 
    df2 = SecondExcelFileReader() 
    return pd.concat([df1, df2]) 

编辑:此 Excel 文件是从 Sybase Oracle SQL Developer 导出的,因此第一张表已经带有标题。我只是复制并粘贴了具有相同标题的第二张纸。另外,我只有第二张纸有问题。

工作表 1:

工作表 2:

请您参考如下方法:

def ExcelFileReader(): 
    xls = pd.ExcelFile('D:/USDataRECENTLY.xls') 
    sheet_num = xls.sheet_names.index(xls.sheet_names[0]) 
    df = pd.read_excel('D:/USDataRECENTLY.xls',sheetname=sheet_num) 
    return df[['months_to_maturity', 'asset_id', 'orig_iss_dt', 'maturity_dt' ,'pay_freq_cd', 'coupon', 'closing_price']] 

或者在这种情况下而不是 sheetname = xls.sheet_names[0]你可以使用 sheetname=0

看起来你的问题是你的第二个工作表名称是“Sheet1”并且基于 ExcelParser 文档“Sheet1”意味着第一张工作表,但在你的情况下它是第二张工作表。 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.ExcelFile.parse.html

更好的实现方式是:

def mergingdataframes(): 
    mergedf= pd.concat(pd.read_excel('D:/USDataRECENTLY.xls', sheetname=[0,1])) 
    mergedf.index = mergedf.index.droplevel(0)# need this to drop dict keys 
    return mergedf