简体   繁体   中英

String replace in python using if statement

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

Use np.where

Ex:

import numpy as np

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM