使用 pandas 查找最多两列或更多列 [英] Find the max of two or more columns with pandas

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

问题描述

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

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).

我应该怎么做?

推荐答案

您可以获得这样的最大值:

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

等等:

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

如果您知道"A"和"B"是仅有的几列,那么您甚至可以逃脱

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

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

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

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

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