Home > Net >  Using functions on multi-indexed dataframe
Using functions on multi-indexed dataframe

Time:03-02

I think this is a basic question but I have not been able to find a usable solution yet. I have some data that is multi-index by month and year as in this attached figure dataframe I want to do some transformations on some columns for each year and month. Let's say I have some function:

def foo(series):
   return series/series.max()

So I would like to apply this function to some column (say, vol) for every month of every year, rather than for all the data at once. Can someone help?

CodePudding user response:

You can use GroupBy.transform, because function return Series:

df['new'] = df.groupby(['year','month'])['vol'].transform(foo)

Alternative here is:

df['new'] = df['vol'].div(df.groupby(['year','month'])['vol'].transform('max'))
  • Related