首页 > 解决方案 > 选择列时的Python panda keyerror

问题描述

我用 .xlsx 文件创建了一个数据框。我想选择一列,但我会得到一个 KeyError,不知道为什么会这样。

df= pd.read_excel('example.xlsx', header=0, axis =1)

  customer_id   end customer name
0 1101          AAB
1 1102          AAC
2 1103          AAD
3 1104          AAE

df['end customer name']
KeyError: 'end customer name'

I've tried:
 - to remove the non-printable characters;
 - to use .iloc (doesn't solve what I want);
 - to convert the object to a string;
 - use thw following argument in pd.read_excel: encoding="utf-8-sig";

发生了什么以及如何解决此问题?非常感谢!

标签: pythonpandasdataframekeyerror

解决方案


在创建数据框时尝试指定列的名称:

df= pd.read_excel('example.xlsx', 
                  header=0, 
                  axis =1,
                  columns=['customer_id','end_customer_name')])

现在您有以下选项来选择您的目标列:

df.iloc[:,1]
df.loc[:,'end_customer_name']
df['end_customer_name']

可能在原始文件中有一些额外的不可见空格.xlsx


推荐阅读