Pandas 条件创建数据框列:基于多个条件最大值 [英] Pandas conditional creation of a dataframe column: based on multiple conditions max
本文介绍了Pandas 条件创建数据框列:基于多个条件最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 df:
dog1 dog2 cat1 cat2 ant1 ant2
0 1 2 3 4 5 6
1 1 2 3 4 0 0
2 3 3 3 3 3 3
3 4 3 2 1 1 0
我想根据以下条件添加一个新列:
I want to add a new column based on the following conditions:
if max(dog1, dog2) > max(cat1, cat2) > max(ant1, ant2) -----> 2
elif max(dog1, dog2) > max(cat1, cat2) -----> 1
elif max(dog1, dog2) < max(cat1, cat2) < max(ant1, ant2) -----> -2
elif max(dog1, dog2) < max(cat1, cat2) -----> -1
else -----> 0
所以它应该变成这样:
dog1 dog2 cat1 cat2 ant1 ant2 new
0 1 2 3 4 5 6 -2
1 1 2 3 4 0 0 -1
2 3 3 3 3 3 3 0
3 4 3 2 1 1 0 2
我知道如何使用 简单的条件,但不是这种最大值.最好的方法是什么?
I know how to do it with straightforward condition, but not this kind with max. What's the best way to do it?
推荐答案
你可以使用 pandas 中的 .max(axis=1)
函数:
You can use .max(axis=1)
function in pandas for it:
conditions = [
(df[['dog1','dog2']].max(axis=1) > df[['cat1','cat2']].max(axis=1)) & (df[['cat1','cat2']].max(axis=1) > df[['ant1','ant2']].max(axis=1)),
(df[['dog1','dog2']].max(axis=1) > df[['cat1','cat2']].max(axis=1)),
(df[['dog1','dog2']].max(axis=1) < df[['cat1','cat2']].max(axis=1)) & (df[['cat1','cat2']].max(axis=1) < df[['ant1','ant2']].max(axis=1)),
(df[['dog1','dog2']].max(axis=1) < df[['cat1','cat2']].max(axis=1))]
choices = [2,1,-2,-1]
df['new'] = np.select(conditions, choices, default=0)
输出:
dog1 dog2 cat1 cat2 ant1 ant2 new
0 1 2 3 4 5 6 -2
1 1 2 3 4 0 0 -1
2 3 3 3 3 3 3 0
3 4 3 2 1 1 0 2
这篇关于Pandas 条件创建数据框列:基于多个条件最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文