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 ?
When creating the DataFrame, you could set the MultiIndex as follows:
This way, the index column is not dropped and still accessible for your
apply.