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

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

问题描述

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

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

一个.如果性别是男性 &pet1=pet2,点数 = 5

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

c.所有其他组合,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 由于运算符优先级,在多个条件周围加上括号.所以当条件为真时 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天全站免登陆