python - 选择列时的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";
发生了什么以及如何解决此问题?非常感谢!
解决方案
在创建数据框时尝试指定列的名称:
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
推荐阅读
- mysql - 在 Account 中拥有唯一的组名,拥有子账户
- grails - 如何从groovy中的字符串中提取带有数字的给定字符串数组
- git - 如何合并两个不同的存储库?
- javascript - 如何确保水平子菜单在屏幕上对齐?
- python - 我需要使用 Python 为 Vlan Id 提取端口
- r - 生成具有不同行数的两个data.frame的所有组合的成对data.frame
- objective-c - 错误:(-215:Assertion failed) !_src.empty() in function 'cvtColor' 同时使用 OpenCV 4.2 和 swift
- aws-lambda - aws api gateway 抛出错误 Cannot GET /patients
- javascript - 通过 ajax 在 Html 中使用来自 Django 的 JsonResponse 变量
- react-native - 如何在反应原生快照轮播中使用视频?也许另一个更好的旋转木马包来反应原生?