Home  >  Article  >  Backend Development  >  How to Find the Maximum Column Value for Each Row in a DataFrame?

How to Find the Maximum Column Value for Each Row in a DataFrame?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-15 01:20:02450browse

How to Find the Maximum Column Value for Each Row in a DataFrame?

Finding Maximum Column Values in a DataFrame

To identify the column with the maximum value for each row in a DataFrame, follow these steps:

Use idxmax() with axis=1:

df.idxmax(axis=1)

This will return a Series containing the column labels of the maximum values for each row.

Create a New Column for Maximum Values:

After finding the maximum column values, create a new column called 'Max' using the Series:

df['Max'] = df.idxmax(axis=1)

Example:

Given the following DataFrame:

Communications and Search Business General Lifestyle
0.745763 0.050847 0.118644 0.084746
0.333333 0.000000 0.583333 0.083333
0.617021 0.042553 0.297872 0.042553

Running the code:

df.idxmax(axis=1)

Will produce the following output:

0    Communications and Search
1          Business
2    Communications and Search
3    Communications and Search
4          Business
dtype: object

Adding this as a new column 'Max':

df['Max'] = df.idxmax(axis=1)

Will result in the following output:

Communications and Search Business General Lifestyle Max
0.745763 0.050847 0.118644 0.084746 Communications and Search
0.333333 0.000000 0.583333 0.083333 Business
0.617021 0.042553 0.297872 0.042553 Communications and Search

The above is the detailed content of How to Find the Maximum Column Value for Each Row in a DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn