Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get column number from label in DataFrame

Tags:

python

pandas

how to get the column number from label in DataFrame, for instance.

import pandas as pd
from pandas import DataFrame

df = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
                'data1': range(6)},
                index=['a1','a2','a3','a4','a5','a6'])
In[31]:df
Out[31]: 
      data1 key
a1      0   b
a2      1   b
a3      2   a
a4      3   c
a5      4   a
a6      5   b

if I run

df.iloc[2,1]

it would return 'a'. the question is, I just know the column label is 'key', how can I get the column number? then I can use df.iloc.

you see, .ix is deprecated in pandas, else I would just use df.ix[2,'key'].

I just know how the solution for the similar question: get column label from column number. for instance,

df.loc['a3',df.iloc[:,[1]].columns]
like image 471
Renke Avatar asked Jul 09 '17 11:07

Renke


1 Answers

You need Index.get_loc or Index.searchsorted:

a = df.columns.get_loc('key')
print (a)
1

a = df.columns.searchsorted('key')
print (a)
1

Then iloc works nice:

a = df.iloc[2, df.columns.get_loc('key')]
print (a)
a
like image 114
jezrael Avatar answered Oct 08 '22 17:10

jezrael