Maison  >  Article  >  développement back-end  >  Comment trouver des valeurs maximales sur plusieurs colonnes dans Pandas ?

Comment trouver des valeurs maximales sur plusieurs colonnes dans Pandas ?

DDD
DDDoriginal
2024-10-17 20:51:30449parcourir

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn