Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Multiindex Dataframe remove maximum

I am struggling with MultiIndex DataFrame in python pandas.

Suppose I have a df like this:

                    count    day     
group    name

  A      Anna        10      Monday
         Beatrice    15      Tuesday

  B      Beatrice    15      Wednesday
         Cecilia     20      Thursday

What I need is to find the maximum in name for each group and remove it from the dataframe.

The final df would look like:

                    count    day     
group    name

  A      Anna        10      Monday

  B      Beatrice    15      Wednesday

Does any of you have any idea how to do this? I am running out of ideas...

Thanks in advance!

EDIT:

What if the original dataframe is:

                   count    day     
group    name

  A      Anna        10      Monday
         Beatrice    15      Tuesday

  B      Beatrice    20      Wednesday
         Cecilia     15      Thursday

and the final df needs to be:

                    count    day     
group    name

  A      Anna        10      Monday

  B      Beatrice    20      Wednesday
like image 556
Piotr Avatar asked Feb 21 '26 00:02

Piotr


1 Answers

UPDATE:

In [386]: idx = (df.reset_index('name')
                   .groupby('group')['name']
                   .max()
                   .reset_index()
                   .values.tolist())

In [387]: df.loc[df.index.difference(idx)]
Out[387]:
                count        day
group name
A     Anna         10     Monday
B     Beatrice     20  Wednesday

In [326]: df.loc[df.index.difference(df.groupby('group')['count'].idxmax())]
Out[326]:
                count        day
group name
A     Anna         10     Monday
B     Beatrice     15  Wednesday

PS most probably there is a better way to do this...

like image 61
MaxU - stop WAR against UA Avatar answered Feb 23 '26 14:02

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!