[英]Pandas conditional creation of a dataframe column: based on multiple conditions
[英]Pandas conditional creation of a dataframe column: based on multiple conditions max
我有一个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
我想根据以下条件添加一个新列:
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
我知道如何在简单的条件下做到这一点,但不是这种情况下最大。 最好的方法是什么?
您可以在 pandas 中使用.max(axis=1)
function :
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)
output:
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
您可以使用apply
文档
def newrow(dog1,dog2,cat1,cat2,ant1,ant2):
if max(dog1, dog2) > max(cat1, cat2) > max(ant1, ant2):
return 2
elif max(dog1, dog2) > max(cat1, cat2):
return 1
elif max(dog1, dog2) < max(cat1, cat2) < max(ant1, ant2):
return -2
elif max(dog1, dog2) < max(cat1, cat2):
return -1
return 0
df['new'] = df.apply(lambda x: newrow(*x), axis=1)
新的df将是
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
看来您正在寻找 np.maximum()。 尝试在最大 numpy找到它希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.