Comment trouver des valeurs maximales sur plusieurs colonnes dans Pandas ?

DDD
Libérer: 2024-10-17 20:51:30
original
446 Les gens l'ont consulté

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

Output:

   A  B  C  D  E
0  1 -2  1  1  1
1  2  8  8  8  8
2  3  1  3  3  3
Copier après la connexion

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!

source:php
Déclaration de ce site Web
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
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!