What is the method to find the maximum value in each row of a dataframe?

I wanted to get a name of a column and the only method I know to do this using the method idmax() which is used in Pandas to find the column with the maximum value in each row of the DataFrame and then count the occurrences of each column to find the column with the highest number of row-wise maximum values. The example code below shows its usage:

import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 
        'B': [4, 5, 6], 
        'C': [3, 5, 2]})

# column with the maximum value in each row
max_cols = df.idxmax(axis=0)

# count the occurrences of each column
max_counts = max_cols.value_counts()

# column with the highest number of row-wise max values
max_col = max_counts.idxmax()

print("Max Value Column: ",
 max_col)
Max Value Column:  2

The problem with this method is that it is showing me number ‘2’ instead of column name. For example, in this code it has to show me column ‘B’ . I believe there may be more efficient ways of doing this, if there are, please provide them with an example code.

1 Like

@nimrah , for this purpose, you can define a lambda function that returns the maximum value of each row using the max() method. Then you can call this lambda function on every row by using the apply() method along the axis=1 of a Pandas dataframe. For Example:

Hello @nimrah, there seems to be logical error in your code in the line where you have used the idxmax() function. You have specified axis = 0 which will make the function search for maximum values row-wise and not column-wise, that is why you are getting a 2 in the output. Here is a correct version of your code which specifies axis = 1 and performs your task column-wise: