Search code examples
pythondataframedatatablemaxpandas-groupby

How to get the corresponding index shown together with the max value


I have this set of table

MonthNum     Trips
1             45000
2             23000
3             78000
4             89000
5             98000
6             96000
7             47000

When I run the following code : I get the result of the max but not the corresponding month. Can I please get some help on this ?

*df = pd.read_csv('data.csv') 
 df = df[['MonthNum','Trips']]
 df = df.groupby('MonthNum').sum().max()
 print(f" The overall busiest month : \n {df}", )*

Returns the following : I need to show the month beside the value The overall busiest month : Trips 98000


Solution

  • If I understand you correctly, you can use .idxmax():

    df = df.groupby("MonthNum", as_index=False).sum()
    print(df.loc[df["Trips"].idxmax()])
    

    Prints:

    MonthNum        5
    Trips       98000
    Name: 4, dtype: int64