Search code examples
pythonpandasdataframemaxargmax

Find the column name which has the maximum value for each row


I have a DataFrame like this one:

Communications and Search   Business    General Lifestyle
0   0.745763    0.050847    0.118644    0.084746
0   0.333333    0.000000    0.583333    0.083333
0   0.617021    0.042553    0.297872    0.042553
0   0.435897    0.000000    0.410256    0.153846
0   0.358974    0.076923    0.410256    0.153846

I want to create a new column comprised of the column labels of each row’s maximum value. The desired output is like this:

Communications and Search   Business    General Lifestyle  Max
0   0.745763    0.050847    0.118644    0.084746           Communications 
0   0.333333    0.000000    0.583333    0.083333           Business  
0   0.617021    0.042553    0.297872    0.042553           Communications 
0   0.435897    0.000000    0.410256    0.153846           Communications 
0   0.358974    0.076923    0.410256    0.153846           Business 

Solution

  • You can use idxmax with axis=1 to find the column with the greatest value on each row:

    >>> df.idxmax(axis=1)
    0    Communications
    1          Business
    2    Communications
    3    Communications
    4          Business
    dtype: object
    

    To create the new column 'Max', use df['Max'] = df.idxmax(axis=1).

    To find the row index at which the maximum value occurs in each column, use df.idxmax() (or equivalently df.idxmax(axis=0)).