
The Pandas DataFrame.idxmax() method returns the column/row label of the maximum value of each row/column of the source DataFrame. NA/null values are excluded.
Syntax –
DataFrame.idxmax(axis=0, skipna=True)
axis – The axis to use. 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise.
skipna – Exclude NA/null values. If an entire row/column is NA, the result will be NA.
Examples –
Let’s create a dataframe to work with.
import pandas as pd
data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}
index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

1 . Find the Index that has Maximum value for Each Columns –
To find the index that has maximum value for each columns, we can use the idxmax() method in pandas.
df.idxmax()
#output
Apple Nov
Orange Aug
Banana May
Mango June
dtype: object
For Apples the highest value is in the month of Nov. For Orange it’s Aug, for Banana it’s May and for Mango it is June.
2 . Find Column that has Max value For Each Row –
To find the column that has max value for each row, we need to set the axis parameter to axis=1 or columns.
df.idxmax(axis=1)
#output
Jan Apple
Feb Apple
Mar Apple
Apr Mango
May Mango
June Mango
Jul Mango
Aug Mango
Sep Mango
Oct Apple
Nov Apple
Dec Apple
dtype: object
IN Jan, Feb and Mar, Apple costs more than any other fruits in this dataframe. Then in Apr, May, June, Jul, Aug and Sep Mango costs more than any other fruits. Then again Apple costs more in the month of Oct, Nov and Dec.