Home  >  Article  >  Backend Development  >  How to find the maximum value within each row of a Pandas DataFrame and add the corresponding column label as a new column?

How to find the maximum value within each row of a Pandas DataFrame and add the corresponding column label as a new column?

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 05:58:03439browse

How to find the maximum value within each row of a Pandas DataFrame and add the corresponding column label as a new column?

Find the maximum value within each row and create a new column with the corresponding column label

You can use pandas to create a DataFrame and find the maximum value for each row. To do this, use the idxmax() function along with the parameter axis=1, which specifies that the maximum should be found across columns for each row. The result will be a Series containing the column labels of the maximum values.

To create a new column with these labels, you can assign the result to a column in the DataFrame. For example:

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'Communications and Search': [0.745763, 0.333333, 0.617021, 0.435897, 0.358974],
                   'Business': [0.050847, 0.000000, 0.042553, 0.000000, 0.076923],
                   'General': [0.118644, 0.583333, 0.297872, 0.410256, 0.410256],
                   'Lifestyle': [0.084746, 0.083333, 0.042553, 0.153846, 0.153846]})

# Find the column label of the maximum value for each row
max_labels = df.idxmax(axis=1)

# Create a new column with the maximum values
df['Max'] = max_labels

# Print the resulting DataFrame
print(df)

Output:

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

This will add a new column called 'Max' to the DataFrame, containing the column labels of the maximum values for each row.

The above is the detailed content of How to find the maximum value within each row of a Pandas DataFrame and add the corresponding column label as a new column?. 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