strimp099 strimp099 - 2 months ago 7
Python Question

Selecting pandas column by location

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)})

DSM DSM
Answer

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.ix[:, 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
Comments