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

Patricia Arquette
Release: 2024-11-15 01:20:02
Original
448 people have browsed it

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)
Copy after login
Copy after login

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)
Copy after login
Copy after login

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)
Copy after login
Copy after login

Will produce the following output:

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

Adding this as a new column 'Max':

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template