Home  >  Article  >  Backend Development  >  How to Combine Maximum Values from Multiple Columns in a DataFrame?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-17 20:57:03162browse

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)

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)

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

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!

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