Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using functions on multi-indexed dataframe

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading