按位置选择 pandas 列 [英] Selecting pandas column by location
本文介绍了按位置选择 pandas 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想通过一个整数来访问命名的 Pandas 列.
您可以使用df.ix[3]
按位置选择一行.
但是如何按整数选择列?
我的数据框:
df=pandas.DataFrame({'a':np.random.rand(5), 'b':np.random.rand(5)})
解决方案
想到的两种方法:
<预><代码>>>>dfA B C D0 0.424634 1.716633 0.282734 2.0869441 -1.325816 2.056277 2.583704 -0.7764032 1.457809 -0.407279 -1.560583 -1.3162463 -0.757134 -1.321025 1.325853 -2.5133734 1.366180 -1.265185 -2.184617 0.881514>>>df.iloc[:, 2]0 0.2827341 2.5837042 -1.5605833 1.3258534 -2.184617名称:C>>>df[df.columns[2]]0 0.2827341 2.5837042 -1.5605833 1.3258534 -2.184617名称:C<小时>
编辑:原始答案建议使用 df.ix[:,2]
但此功能现已弃用.用户应该切换到 df.iloc[:,2]
.
I'm simply trying to access named pandas columns by an integer.
You can select a row by location using df.ix[3]
.
But how to select a column by integer?
My dataframe:
df=pandas.DataFrame({'a':np.random.rand(5), 'b':np.random.rand(5)})
解决方案
Two approaches that come to mind:
>>> 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
Edit: The original answer suggested the use of df.ix[:,2]
but this function is now deprecated. Users should switch to df.iloc[:,2]
.
这篇关于按位置选择 pandas 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文