请参阅文档的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!
或者干脆'df.ix [0, 'A']' – alko
注意,'df [0] ['A']'实际上是没有意义的,因为这个语法按名称访问列,并且df中没有名称为'0'的列。 – alko