Home > Net >  How do i select a whole row based on the highest value of a column
How do i select a whole row based on the highest value of a column

Time:04-16

Im trying to print the whole row with the highest number of casualties in this data. Currently i can only print the highest number of casualties and not the whole row using the below code, does anyone know how to change it to what i need;

#this code give me the highest casualty number but i also need the LSOA it comes from
sorted_df = accidents.sort_values('Number_of_Casualties', ascending=False)
sorted_df['Number_of_Casualties'].max()

accidents data preview (pandas);

Accident_Index  Number_of_Casualties LSOA_of_Accident_Location
0               51                   E01004762
1               52                   E01003117
2               43                   E01004760
3               23                   E01003113
4               44                   E01004732
5               38                   E01003111

What I'm looking for is to print the whole of row 2 here rather than just the 52 value

CodePudding user response:

print(df.loc[df['Number_of_Casualties'] == df['Number_of_Casualties'].max()])

   Accident_Index  Number_of_Casualties LSOA_of_Accident_Location
1               1                    52                 E01003117

CodePudding user response:

Why no just sorted_df.iloc[0] ? You already sorted it. or if you want in a dataframe: sorted_df.iloc[[0]]

If you don't want a sorted_df and just want to pick the max, then @jch's answer should work.

  • Related