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

Patricia Arquette
发布: 2024-10-17 20:57:03
原创
236 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板