简体   繁体   English

如果满足条件,如何将两种不同的功能应用于一列?

[英]How to apply two different functions to one column if meets the condition?

I need to apply 2 different functions to 1 columns if it meets a condition.如果满足条件,我需要将 2 个不同的功能应用于 1 列。 My dataframe looks like this.我的 dataframe 看起来像这样。 I want to apply the functions to the column produce: veg_pro if the category is a vegetable and fruit_pro if it's a fruit.我想将函数应用于列生产:如果类别是蔬菜,则为 veg_pro,如果是水果,则为 fruit_pro。

Produce            Category
apple is good      fruit
corn is bad        vegetable
beans is good      vegetable
grape if good      fruit

My functions look like this:我的功能如下所示:

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().

instead of using apply on one column use it on the dataframe like this:而不是在一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.

相关问题 如何将 if 条件应用于两个不同的列并将结果放入新列 - How to apply if condition to two different columns and put the result to a new column 仅当一列满足特定条件时如何合并DataFrame - How to merge DataFrames only if one column meets a certain condition 熊猫:按满足条件的列分组 - Pandas: Group by a column that meets a condition 如何使用pandas Groupby将不同的聚合函数应用于同一列 - How to apply different aggregation functions to same column by using pandas Groupby 如何根据不同列的条件返回一列 - how to return one column based on a condition depending on a different column 如何更改满足给定条件的列值,同时保持该列不满足条件的值 - How to change column values that meets a given condition while maintaining the values for that column that don't meet the condition 如何在有条件的情况下应用公式以生成新列并应用两种类型的排名? - How to apply formulas on condition to generate a new column and apply two types of ranking? 按 ID 分组并对一列的值应用条件 - Group by ID and apply a condition on the value of one column 根据Python中的条件应用两个装饰器中的一个 - Apply one of two decorators according to a condition in Python 如果另一列中的行满足条件则填充nan - Filling nan if row in another column meets condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM