"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Find Maximum Values across Multiple Columns in Pandas?

How to Find Maximum Values across Multiple Columns in Pandas?

Published on 2024-11-05
Browse:931

How to Find Maximum Values across Multiple Columns in Pandas?

Finding Maximum Values across Multiple Columns in Pandas

To determine the maximum values across multiple columns in a pandas DataFrame, various approaches can be employed. Here's how you can achieve this:

Using the max() Function with Specified Columns

This method involves explicitly selecting the desired columns and applying the max() function:

df[["A", "B"]]
df[["A", "B"]].max(axis=1)

This will create a new column with the maximum values from columns A and B.

Using the max() Function with All Columns

If you're sure that the DataFrame contains only the columns you want to find the maximum for, you can use the following simplified syntax:

df.max(axis=1)

This will automatically consider all columns and output a column with the maximum values.

Using the apply() Function

Alternatively, you can utilize the apply() function with the max function:

df.apply(max, axis=1)

This will also create a column with the maximum values for each row.

Example:

Let's illustrate these approaches with an example:

import pandas as pd

df = pd.DataFrame({"A": [1, 2, 3], "B": [-2, 8, 1]})

# Using max() with specified columns
df["C"] = df[["A", "B"]].max(axis=1)

# Using max() with all columns
df["D"] = df.max(axis=1)

# Using apply()
df["E"] = df.apply(max, axis=1)

print(df)

Output:

   A  B  C  D  E
0  1 -2  1  1  1
1  2  8  8  8  8
2  3  1  3  3  3
Release Statement This article is reprinted at: 1729169358 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3