通过位置选择pandas列
我只是想通过数字来访问命名的 pandas 列。
你可以使用 df.ix[3]
来通过位置选择一行。
但是,怎么通过数字选择一列呢?
我的数据框:
df=pandas.DataFrame({'a':np.random.rand(5), 'b':np.random.rand(5)})
7 个回答
28
你可以使用基于标签的方法,比如 .loc,或者基于索引的方法,比如 .iloc,来进行列切片,包括选择一系列的列:
In [50]: import pandas as pd
In [51]: import numpy as np
In [52]: df = pd.DataFrame(np.random.rand(4,4), columns = list('abcd'))
In [53]: df
Out[53]:
a b c d
0 0.806811 0.187630 0.978159 0.317261
1 0.738792 0.862661 0.580592 0.010177
2 0.224633 0.342579 0.214512 0.375147
3 0.875262 0.151867 0.071244 0.893735
In [54]: df.loc[:, ["a", "b", "d"]] ### Selective columns based slicing
Out[54]:
a b d
0 0.806811 0.187630 0.317261
1 0.738792 0.862661 0.010177
2 0.224633 0.342579 0.375147
3 0.875262 0.151867 0.893735
In [55]: df.loc[:, "a":"c"] ### Selective label based column ranges slicing
Out[55]:
a b c
0 0.806811 0.187630 0.978159
1 0.738792 0.862661 0.580592
2 0.224633 0.342579 0.214512
3 0.875262 0.151867 0.071244
In [56]: df.iloc[:, 0:3] ### Selective index based column ranges slicing
Out[56]:
a b c
0 0.806811 0.187630 0.978159
1 0.738792 0.862661 0.580592
2 0.224633 0.342579 0.214512
3 0.875262 0.151867 0.071244
66
你也可以用 df.icol(n)
通过数字来访问某一列。
更新:icol
这个方法已经不再推荐使用了,你可以通过以下方式实现相同的功能:
df.iloc[:, n] # to access the column at the nth position
234
我想到两种方法:
>>> df
A B C D
0 0.424634 1.716633 0.282734 2.086944
1 -1.325816 2.056277 2.583704 -0.776403
2 1.457809 -0.407279 -1.560583 -1.316246
3 -0.757134 -1.321025 1.325853 -2.513373
4 1.366180 -1.265185 -2.184617 0.881514
>>> df.iloc[:, 2]
0 0.282734
1 2.583704
2 -1.560583
3 1.325853
4 -2.184617
Name: C
>>> df[df.columns[2]]
0 0.282734
1 2.583704
2 -1.560583
3 1.325853
4 -2.184617
Name: C
补充说明: 原来的回答提到了使用 df.ix[:,2]
,但这个功能现在已经不推荐使用了。用户应该改用 df.iloc[:,2]
。