Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index value in pandas MultiIndex data frame?

Tags:

python

pandas

df = pd.DataFrame({'a':[2,3,5], 'b':[1,2,3], 'c':[12,13,14]})
df.set_index(['a','b'], inplace=True)
display(df)
s = df.iloc[1]
# How to get 'a' and 'b' value from s? 

It is so annoying that ones columns become indices we cannot simply use df['colname'] to fetch values.

Does it encourage we use set_index(drop=False)?

like image 222
colinfang Avatar asked Feb 25 '14 13:02

colinfang


2 Answers

When I print s I get

In [8]: s = df.iloc[1]

In [9]: s
Out[9]:  
c    13
Name: (3, 2), dtype: int64

which has a and b in the name part, which you can access with:

s.name

Something else that you can do is

df.index.values

and specifically for your iloc[1]

df.index.values[1]

Does this help? Other than this I am not sure what you are looking for.

like image 119
Wesley Bowman Avatar answered Sep 23 '22 06:09

Wesley Bowman


if you want to get "a" and "b"

df.index.names

gives: FrozenList(['a', 'b'])

like image 26
ricmarchao Avatar answered Sep 22 '22 06:09

ricmarchao