[英]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.尝试根据列值替换字符串,得到错误 ValueError: The truth value of a Series 不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all().
使用 a.empty、a.bool()、a.item()、a.any() 或 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().
使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
Just I need to check the string and replace it with another column value if matches只是我需要检查字符串并在匹配时将其替换为另一个列值
Use np.where
使用
np.where
Ex:前任:
import numpy as np
df['Target'] = np.where(df['Target'] == "U", df['Action'], df['Target'])
You can use pandas.DataFrame.loc
:您可以使用
pandas.DataFrame.loc
:
df.loc[df["Target"] == 'U', "Target"] = df["Action"]
You can also use pandas.DataFrame.where
您还可以使用
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 ==
.请注意,在这种情况下,不满足条件的细胞所取代,这就是为什么你必须使用
!=
而不是==
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.