Home  >  Article  >  Backend Development  >  How to Find Maximum Values across Multiple Columns in Pandas?

How to Find Maximum Values across Multiple Columns in Pandas?

DDD
DDDOriginal
2024-10-17 20:51:30521browse

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:

<code class="python">df[["A", "B"]]
df[["A", "B"]].max(axis=1)</code>

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:

<code class="python">df.max(axis=1)</code>

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:

<code class="python">df.apply(max, axis=1)</code>

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

Example:

Let's illustrate these approaches with an example:

<code class="python">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)</code>

Output:

   A  B  C  D  E
0  1 -2  1  1  1
1  2  8  8  8  8
2  3  1  3  3  3

The above is the detailed content of How to Find Maximum Values across Multiple Columns in Pandas?. 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