2013-12-12 26 views
2

这是一个简单的noob问题,但它令我烦恼。在教程之后,我想选择列“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']) 

回答

3

因为df[0]['A']在索引A意味着柱0;你需要使用df.iloc[0]['A'],或df['A'][0],或者df.ix[0]['A']

看到here的索引和切片。

请参阅here以获取副本而不是视图。

+3

或者干脆'df.ix [0, 'A']' – alko

+0

注意,'df [0] ['A']'实际上是没有意义的,因为这个语法按名称访问列,并且df中没有名称为'0'的列。 – alko

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。

值得强调的是,分配garaunteed一个LOC/ILOC/IX工作,但链接时可以失败:

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

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

安迪,重新链接,DF [col] [行]应该避免是正确的,还是只有在切片以及DF [col] [row1:row2]? –

+0

@WoodyPride如果你正在做分配链接不保证工作。我会避免'DF [col] [row]':) –

+0

这是一个打击!我现在必须回去检查一年的工作价值。哎呀! –