首页  >  文章  >  后端开发  >  如何合并数据框中多列的最大值?

如何合并数据框中多列的最大值?

Patricia Arquette
Patricia Arquette原创
2024-10-17 20:57:03162浏览

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

以上是如何合并数据框中多列的最大值?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn