Home > Blockchain >  Numpy where condition when met must modify the original value, if not original value must remain
Numpy where condition when met must modify the original value, if not original value must remain

Time:11-15

I have the following dataframe:

Policy_id Value 
     A           xyz
     B           abc
     A           pqr
     C           lmn

And I want to use np.where() such that whenever the policy_id is equal to A the corresponding value must be appended with a *.

Policy_id    Value 
     A           xyz*
     B           abc
     A           pqr*
     C           lmn

How do I achieve this?

CodePudding user response:

Try

df['new'] = np.where(df['Policy_id'].eq('A'),df['Value'] '*',df['Value'])

CodePudding user response:

If you want to modify your dataframe in place and use np.where:

df['Value']  = np.where(df['Policy_id'].eq('A'), '*', '')

output:

  Policy_id Value
0         A  xyz*
1         B   abc
2         A  pqr*
3         C   lmn

CodePudding user response:

(I just noticed you specifically asked about how to use np.where, but I will leave this Series.mask/Series.where answer for reference.)


  • Use Series.mask

    Replace df['Value'] with df['Value'] '*' if df['Policy_id'.eq('A'):

    df['Value'] = df['Value'].mask(df['Policy_id'].eq('A'), df['Value']   '*')
    
  • Or Series.where

    Inverse of masking, so flip the condition from eq to ne:

    df['Value'] = df['Value'].where(df['Policy_id'].ne('A'), df['Value']   '*')
    

Note that inplace is possible but not recommended and will soon be deprecated:

df['Value'].mask(df['Policy_id'].eq('A'), df['Value']   '*', inplace=True)
  • Related