+

Python | Pandas dataframe.idxmax ()

The Pandas function dataframe.idxmax() returns the index of the first occurrence of the maximum along the requested axis. When the index of the maximum value at any index is found, all NA / null values ​​are excluded.

Syntax: DataFrame.idxmax (axis = 0, skipna = True)

Parameters:
axis: 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

Returns: idxmax: Series

Example # 1 : Use idxmax () to find the index of the maximum value along the index axis.

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ "A" : [ 4 , 5 , 2 , 6 ], 

  "B" : [ 11 , 2 , 5 , 8 ],

"C" : [ 1 , 8 , 66 , 4 ]})

 
# Print the data frame
df

Now apply idxmax () along the index axis.

# using the idxmax () function.

df.idxmax (axis = 0 )

Output:

If we look at the values ​​in the data frame, we can check the result returned by the function. The function returned a pandas series object containing the index of the maximum value in each column.

Example # 2: Use idxmax () to find the index of the maximum value along the axis column. The data frame contains NA values.

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ "A" : [ 4 , 5 , 2 , None ],

"B" : [ 11 , 2 , None , 8 ], 

"C" : [ 1 , 8 , 66 , 4 ]})

 
# Skipna = True will skip all Na values ​​
# find the maximum along the column axis

df.idxmax (axis = 1 , skipna = True )

Output:

The output is a series of pandas containing a column label for each row that has a maximum value.

Get Solution for free from DataCamp guru