python - Pandas: How do I assign values based on multiple conditions for existing columns? -


i create new column numerical value based on following conditions:

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

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

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

i end result follows:

    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 

how accomplish this?

you can using np.where, conditions use bitwise & , | and , or parentheses around multiple conditions due operator precedence. condition true 5 returned , 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 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -