在以下情况下,Python (3.5) pandas (0.22.0) 中获取 Key 错误。 例如导入此 csv 数据:
'First', 'Name', 'Second', 'Number', 'Another Number', 'Random Exclamation', 'Time', 'Left', 'Anyway'
91004, 'Freddy', 1.518990585, 1.1000082, 5790, 'Hooray', 7241606319.947, 1939238254.77354879, 1.215094577191377
我这样导入它:
test=pd.read_csv('test.csv')
我可以做到这一点:
>>> test.dtypes
'First' int64
'Name' object
'Second' float64
'Number' float64
'Another Number' int64
'Random Exclamation' object
'Time' float64
'Left' float64
'Anyway' float64
dtype: object
还有这个:
>>> test.loc[0]
'First' 91004
'Name' 'Freddy'
'Second' 1.51899
'Number' 1.10001
'Another Number' 5790
'Random Exclamation' 'Hooray'
'Time' 7.24161e+09
'Left' 1.93924e+09
'Anyway' 1.21509
Name: 0, dtype: object
还有这个:
>>>test.loc[0][0]
91004
但是如果我尝试这个:
>>>test.loc['First']
或者这个:
>>>test.loc[0, 'First']
我明白了:
KeyError: 'the label [First] is not in the [index]'
这是我的问题最简洁的例子。我已经尝试了多种尝试通过标签访问数据的组合,我不会让您感到厌烦,但它们都不起作用。我尝试过很多类似的测试数据,并偶尔删除 csv 中的所有空格,但这没有什么区别。 我究竟如何通过标签访问框架中的数据? 我是 Pandas 新手,已经在谷歌上搜索了几个小时。这通常意味着我非常愚蠢,所以任何帮助都很感激。谢谢。
最佳答案
您缺少内部引号。在Python中,引号(单引号或双引号)可能表示一个字符串,因此您需要使用双外引号和单内引号。试试这个:
test.loc[0, "'First'"]
我强烈建议您通过删除标点符号和前导/尾随空格来清理列名:
test.columns = test.columns.str.replace('[^\w\s]','').str.strip()
关于python - Pandas 按标签查找内容不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50277108/