Home > database >  How do I print only the 3rd most highest value from this series?
How do I print only the 3rd most highest value from this series?

Time:08-06

Most_Calori_Burner.nlargest(3)

How do I print only the 3rd most highest value from this series? this code is giving the top 3 values

My series

CodePudding user response:

You could do:

import pandas as pd
df = pd.DataFrame({'Id': [150351, 456385, 456983, 150351], 'Calories': [456983, 45689, 23586, 45683]})
series = df.groupby('Id')['Calories'].sum()
third_largest = series.sort_values().tolist()[-3]  # output is the third largest value for the Calories column after groupby
index = series[series == third_largest].index[0]  # index of third-largest element

This sorts the series (in ascending order) and then gives you the third to last element, which is the third largest.

  • Related