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
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