bigbug
bigbug

Reputation: 59544

How to groupby the first level index and apply function to the second index in Pandas

I have multilevel dataframe 'df' like this :

             col1 col2
first second
a        0    5    5
         1    5    5
         2    5    5
b        0    5    5
         1    5    5

And I want to apply a function func (exp: 'lambda x: x*10') to second, somewhat like :

df.groupby(level='first').second.apply(func)

and result will lokk like:

             col1 col2
first second
a        0    5    5
         10   5    5
         20   5    5
b        0    5    5
         10   5    5

The above command not work for second is not a column, so .second is not accepted by Pandas .

I don't want to do that by df.reset_index() , blablabla..., then finally df.set_index(). I prefer to do it in one command, How to do ?

Upvotes: 3

Views: 8059

Answers (2)

JoeCondron
JoeCondron

Reputation: 8906

You can use the set_levels method of the index to change the values in a given level. So for a given func and level you can do:

new_values = map(func, df.index.get_level_values(level))
df.index.set_levels(new_values, level, inplace=True)

Upvotes: 2

Def_Os
Def_Os

Reputation: 5467

When creating the DataFrame, you could set the MultiIndex as follows:

df.set_index(['first', 'second'], drop=False)

This way, the index column is not dropped and still accessible for your apply.

Upvotes: 2

Related Questions