per level math operation in multilevel pandas dataframe?

Question:

I have a dataframe with index of (a, b, c),columns: D to H. I have sorted the dataframe by [a, E] Now I want to normalize the dataframe like this:

for va in df.index.get_level_values('a').unique():
    df[df['a']==va] = df[df['a']==va]/(df[df['a']==va].iloc[0])

I wonder is there a more efficient way or even a builtin method for this kind of operation?

maybe something like reversed groupby('xxxx').apply(). Because the groupby is just aggregate. I probably need something reversed.

Asked By: Wang

||

Answers:

Based on my understanding, how about this?

df = df.groupby(['a'])['D', 'E', 'F', 'G', 'H'].transform(lambda x: x.div(x.iloc[0]))

if you provide an example we can better assist.

Answered By: Phoenix
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.