1
votes

Trying to replace a string based on column value, getting the error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

if df['Target'] == 'U':
   df['Target'] = df['Action'] 

Getting the Error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Just I need to check the string and replace it with another column value if matches

2

2 Answers

2
votes

Use np.where

Ex:

import numpy as np

df['Target'] = np.where(df['Target'] == "U", df['Action'], df['Target'])
0
votes

You can use pandas.DataFrame.loc:

df.loc[df["Target"] == 'U', "Target"] = df["Action"]

You can also use pandas.DataFrame.where

df["Target"].where(df["Target"] != 'U', df["Action"], inplace = True)

Note that in this case the cells that does NOT satisfy the condition are replaced, that's why you have to use != instead of ==.