Home > Blockchain >  per level math operation in multilevel pandas dataframe?
per level math operation in multilevel pandas dataframe?

Time:12-29

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.

CodePudding user response:

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.

  • Related