python - Pandas 按标签查找内容不起作用

标签 python string python-3.x pandas

在以下情况下,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/

相关文章:

python - pyplot根据两条曲线的变化率填充它们

python - Pyspark - 将列转换为列表

python - 为什么我不能在一个类中连接 'str' 和 'instance' 对象?

c - 如何在C中输入n个字符串(n由用户输入)而不分配n个空格?

python-2.7 - Python Numpy 安装 Windows 10 64 位

python - 当模型位于不同应用程序中时,ManytoMany 字段 django 模板

用于并发读写的 Ruby StringIO

python - 用条目小部件替换 python tkinter 标签小部件

python - 我们如何改变当前的 __main__

Python 3.x 舍入行为