请参阅文档的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!