pandas :如何基于多个条件为现有列分配值? [英] Pandas: How do I assign values based on multiple conditions for existing columns?

查看:48
本文介绍了 pandas :如何基于多个条件为现有列分配值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据以下条件创建一个具有数值的新列:

I would like to create a new column with a numerical value based on the following conditions:

a.如果性别是男性& pet1 = pet2,分数= 5

a. if gender is male & pet1=pet2, points = 5

b.如果性别是女性& (pet1是'cat'或pet1 ='dog'),点数= 5

b. if gender is female & (pet1 is 'cat' or pet1='dog'), points = 5

c.所有其他组合,点= 0

c. all other combinations, points = 0

    gender    pet1      pet2
0   male      dog       dog
1   male      cat       cat
2   male      dog       cat
3   female    cat       squirrel
4   female    dog       dog
5   female    squirrel  cat
6   squirrel  dog       cat

我希望最终结果如下:

    gender    pet1      pet2      points
0   male      dog       dog       5
1   male      cat       cat       5
2   male      dog       cat       0
3   female    cat       squirrel  5
4   female    dog       dog       5
5   female    squirrel  cat       0
6   squirrel  dog       cat       0

我如何做到这一点?

推荐答案

您可以使用np.where进行此操作,条件对于andor使用按位&|,并在括号周围加上倍数由于操作员优先而产生的条件.因此,在条件为true的情况下,返回5,否则返回0:

You can do this using np.where, the conditions use bitwise & and | for and and or with parentheses around the multiple conditions due to operator precedence. So where the condition is true 5 is returned and 0 otherwise:

In [29]:
df['points'] = np.where( ( (df['gender'] == 'male') & (df['pet1'] == df['pet2'] ) ) | ( (df['gender'] == 'female') & (df['pet1'].isin(['cat','dog'] ) ) ), 5, 0)
df

Out[29]:
     gender      pet1      pet2  points
0      male       dog       dog       5
1      male       cat       cat       5
2      male       dog       cat       0
3    female       cat  squirrel       5
4    female       dog       dog       5
5    female  squirrel       cat       0
6  squirrel       dog       cat       0

这篇关于 pandas :如何基于多个条件为现有列分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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