![](/img/trans.png)
[英]How to apply if condition to two different columns and put the result to a new column
[英]How to apply two different functions to one column if meets the condition?
如果满足条件,我需要将 2 个不同的功能应用于 1 列。 我的 dataframe 看起来像这样。 我想将函数应用于列生产:如果类别是蔬菜,则为 veg_pro,如果是水果,则为 fruit_pro。
Produce Category
apple is good fruit
corn is bad vegetable
beans is good vegetable
grape if good fruit
我的功能如下所示:
def veg_pro(text):
reg_tokenizer = RegexpTokenizer('\s+', gaps = True)
terms = reg_tokenizer.tokenize(text)
return terms
def fruit_pro(text):
reg_tokenizer = RegexpTokenizer(“[\w+.]+“)
terms = reg_tokenizer.tokenize(text)
return terms
df['produce']= df['produce'].apply(lambda x:
veg_pro(x) if df['Category'] =='vegetable’ else
fruit_pro(x))
ValueError: The truth value of a Series is ambiguous. Use
a.empty, a.bool(), a.item(), a.any() or a.all().
而不是在一column
上使用apply
它在dataframe
上使用它,如下所示:
df['produce']= df.apply(lambda x:
veg_pro(x["produce"]) if x["Category"] =="vegetable" else fruit_pro(x["produce"]),axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.