无法在熊猫中选择一个细胞

时间:2013-12-12 22:58:02

标签: python python-3.x pandas

这是一个简单的菜鸟问题,但令我感到烦恼。在教程之后,我想选择“A”列中的第一个值。教程说运行print(df[0]['A'])但是Python3给了我一个错误。但是,如果我使用print(df[0:1]['A']),它会完美运行。那是为什么?

以下是复制的完整代码:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100, 3), index=pd.date_range('1/1/2000', periods=100), columns=['A', 'B', 'C'])

print(df[0:1]['A'])

2 个答案:

答案 0 :(得分:3)

因为df[0]['A']表示索引为0的列A;您需要使用df.iloc[0]['A']df['A'][0]df.ix[0]['A']

请参阅here了解索引和切片。

请参阅here了解何时获得副本而不是视图。

答案 1 :(得分:3)

请参阅文档的selecting ranges部分。如上所述:

  

使用DataFrame,在[]内部切片切片。这主要是为了方便,因为它是一种常见的操作。

另一方面,这是不一致的。

值得一提的是,你可以经常使用loc / iloc:

In [11]: df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=['A', 'B'])

In [12]: df['A']
Out[12]: 
0    1
1    3
2    5
Name: A, dtype: int64

In [13]: df.loc[:, 'A']  # equivalently
Out[13]: 
0    1
1    3
2    5
Name: A, dtype: int64

In [14]: df.iloc[:, 0]  # accessing column by position
Out[14]: 
0    1
1    3
2    5
Name: A, dtype: int64

值得一提的是切片的另一个不一致之处:

In [15]: df.loc[0:1, 'A']
Out[15]: 
0    1
1    3
dtype: int64

In [16]: df.iloc[0:1, 0]  # doesn't include 1th row
Out[16]: 
0    1
dtype: int64

要使用位置和标签进行选择,请使用ix:

In [17]: df.ix[0:1, 'A']
Out[17]: 
0    1
1    3
Name: A, dtype: int64

注意标签优先于ix。

值得强调的是,使用一个loc / iloc / ix可以很好地分配任务,但链接时可能失败:

In [18]: df.ix[0:1, 'A'] = 7  # works

In [19]: df['A'][0:1] = 7  # *sometimes* works, avoid!