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.maskReplace
df['Value']withdf['Value'] '*'ifdf['Policy_id'.eq('A'):df['Value'] = df['Value'].mask(df['Policy_id'].eq('A'), df['Value'] '*')Or
Series.whereInverse of masking, so flip the condition from
eqtone: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)
