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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With