【问题标题】:how can I use pandas assign function with a personal defined function?如何将熊猫分配功能与个人定义的功能一起使用?
【发布时间】:2020-04-20 13:22:31
【问题描述】:

这是我的代码

def calculsComplexesPlusieursColonnes(total_bill,tip,sex):
        if sex=="Female":return total_bill+tip
        else : return total_bill+2*tip

    tips['résultat'] = tips.apply(lambda row: calculsComplexesPlusieursColonnes(row['total_bill'], row['tip'],row['sex']), axis=1)
    tips=tips.assign(résultat_bis=lambda row: calculsComplexesPlusieursColonnes(row.total_bill,row.tip,row.sex))

我尝试了两种使用函数创建新变量的方法:第一种工作正常(var résultat),但第二种(var résultat_bis),最后一行代码不起作用:我明白了

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我应该怎么做才能让它工作? 您真诚的 Loïc

【问题讨论】:

  • 请告诉我我的解决方案是否有效

标签: python pandas assign


【解决方案1】:

你只需要:

tips['résultat']=( tips['sex'].ne('Female')
                              .astype(int)
                              .add(1)
                              .mul(tips['tip'])
                              .add(tips['total_bill']) )

基本上使用Series.ne + Series.astype 我们创建了一个系列,其中性别不等于女性,而性别不等于女性,则为 0。然后我们把这个数列加1,剩下的就只剩下相乘加对应的数列了

我建议你看看: When should I ever want use applyTruth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2021-05-16
    • 2015-05-21
    • 1970-01-01
    • 2016-11-15
    相关资源
    最近更新 更多