使用if语句在python中替换字符串

问题描述:

尝试根据列值替换字符串,但出现错误 ValueError:系列的真值不明确.使用a.empty,a.bool(),a.item(),a.any()或a.all().

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'] 

获取错误 ValueError:系列的真值不明确.使用a.empty,a.bool(),a.item(),a.any()或a.all().

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

使用np.where

例如:

import numpy as np

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