簡體   English   中英

如果滿足條件,如何將兩種不同的功能應用於一列?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM