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

Susan Sarandon
Release: 2024-11-15 17:17:03
Original
801 people have browsed it

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

Finding the Maximum Value Column for Each Row

Consider a DataFrame with multiple columns containing numerical values. To identify the column that holds the maximum value for each row, implement the following steps:

  1. Identify the Maximum Value in Each Row:

Use the idxmax function along with the axis=1 parameter to determine the column where the maximum value occurs in each row:

column_with_max_value = df.idxmax(axis=1)
Copy after login
  1. Create a New Column with Column Labels:

To create a new column labeled 'Max' that contains the column labels associated with the maximum values, assign it as such:

df['Max'] = column_with_max_value
Copy after login
  1. Display the Output:

The resulting DataFrame will include an additional column labeled 'Max', which indicates the column holding the greatest value for each row:

print(df)
Copy after login

Additional Notes:

  • To find the row index of the maximum value in each column, use df.idxmax(axis=0) instead of axis=1.
  • This technique can be applied to DataFrames with any number of columns and rows.

The above is the detailed content of How to Find the Column with the Maximum 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