用 Pandas 找出两列或更多列的最大值 [英] Find the max of two or more columns with pandas

查看:68
本文介绍了用 Pandas 找出两列或更多列的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 A,B 列的数据框.我需要创建一列 C 以便为每个记录/行:

C = max(A, B).

我应该怎么做?

解决方案

你可以这样得到最大值:

<预><代码>>>>将熊猫导入为 pd>>>df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})>>>df甲乙0 1 -21 2 82 3 1>>>df[["A", "B"]]甲乙0 1 -21 2 82 3 1>>>df[["A", "B"]].max(axis=1)0 11 82 3

等等:

<预><代码>>>>df["C"] = df[["A", "B"]].max(axis=1)>>>df乙丙0 1 -2 11 2 8 82 3 1 3

如果您知道A"和B"是唯一的列,您甚至可以逃脱

<预><代码>>>>df["C"] = df.max(axis=1)

我猜你也可以使用 .apply(max,axis=1).

I have a dataframe with columns A,B. I need to create a column C such that for every record / row:

C = max(A, B).

How should I go about doing this?

解决方案

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

这篇关于用 Pandas 找出两列或更多列的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆