Sort examples in pandas dataframe by maximum of three columsn

You can calculate the max, assign to new column and sort:

df['max_val'] = df.filter(like='ev').max(1)
df.sort_values('max_val')

If you don’t want to modify your data, you can sort the series and use loc or use argsort and iloc

max_val = df.filter(like='ev').max(1)

df.loc[max_val.sort_values(ascending=False).index]

# also
# df.iloc[np.argsort(-max_val, axis=1)]

Output:

  home_team_name away_team_name       ev1       ev0       ev2
3          Parma     Fiorentina  0.570120 -0.078788 -0.364922
4          Lazio       Juventus  0.483111 -0.040047 -0.284971
1       Cagliari      Sampdoria  0.278430 -0.086284 -0.243369
0       Sassuolo        Udinese  0.213624 -0.152282 -0.306609
2      Benevento         Spezia -0.079299 -0.000337  0.078663

For the column names with max values, use idxmax:

df['max_col'] = df.filter(like='ev').idxmax(1)

Output:

  home_team_name away_team_name       ev1       ev0       ev2 max_col
0       Sassuolo        Udinese  0.213624 -0.152282 -0.306609     ev1
1       Cagliari      Sampdoria  0.278430 -0.086284 -0.243369     ev1
2      Benevento         Spezia -0.079299 -0.000337  0.078663     ev2
3          Parma     Fiorentina  0.570120 -0.078788 -0.364922     ev1
4          Lazio       Juventus  0.483111 -0.040047 -0.284971     ev1

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top