TuMama
TuMama

Reputation: 471

Get the entire row with a max specific value,Pandas

neighbourhood      room_type           value
Agios Loukas       Entire home/apt      69
                   Private room         11
                   Shared room           1
Agios Nikolaos     Entire home/apt     193
                   Private room         33
Akadimia Platonos  Entire home/apt      45
                   Private room         10
                   Shared room           1 

What is the best way to take the entire row with max value. For example i want to take

Agios Loukas       Entire home/apt      69 
Agios Nikolaos     Entire home/apt     193
Akadimia Platonos  Entire home/apt      45

Thank you and sorry for my english

Upvotes: 0

Views: 135

Answers (2)

anky
anky

Reputation: 75150

I believe you need;

Either groupby on the first level and idxmax with df.loc[]

out = df.loc[df.groupby(level=0)['value'].idxmax()]
print(out)

                                   value
neighbourhood     room_type             
Agios Loukas      Entire home/apt     69
Agios Nikolaos    Entire home/apt    193
Akadimia Platonos Entire home/apt     45

Or:

groupby+transform with max and then equals operator to compate and select the rows

out1 = df[df['value'].eq(df.groupby('neighbourhood')['value'].transform('max'))]
print(out1)

                                   value
neighbourhood     room_type             
Agios Loukas      Entire home/apt     69
Agios Nikolaos    Entire home/apt    193
Akadimia Platonos Entire home/apt     45

Upvotes: 3

Peter Prescott
Peter Prescott

Reputation: 908

Use .max() to get the max value of a column, and put it inside of a df.loc[] request to get all the rows with that value. Something like this:

df.loc[df['value'] == df['value'].max()]

Upvotes: 0

Related Questions