How to Combine Maximum Values from Multiple Columns in a DataFrame?

Patricia Arquette
Release: 2024-10-17 20:57:03
Original
171 people have browsed it

How to Combine Maximum Values from Multiple Columns in a DataFrame?

Getting the Maximum Value from Multiple DataFrame Columns

When working with dataframes, having a consolidated column containing the maximum values from multiple other columns can be useful. One such instance is obtaining the maximum value between columns A and B, as illustrated in this example:

import pandas as pd

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

print("Original DataFrame:")
print(df)
Copy after login

Our goal is to create a new column C containing the maximum value for each row between columns A and B. To achieve this, we can use the following steps:

print("\nMaximum values between A and B:")
df["C"] = df[["A", "B"]].max(axis=1)
print(df)
Copy after login

Explanation:

  1. We fetch the maximum value between columns A and B for each row using .max(axis=1) and store it in a new column titled "C".
  2. Optionally, we could also utilize .max(axis=1) directly on the dataframe.
  3. Using .apply(max, axis=1) is another viable approach.

As a result, we obtain a modified dataframe with the "C" column containing the desired maximum values:

Original DataFrame:
   A  B
0  1 -2
1  2  8
2  3  1

Maximum values between A and B:
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3
Copy after login

The above is the detailed content of How to Combine Maximum Values from Multiple Columns in a DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!