1

here is my code

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

I try 2 ways of creating a new variable using a function : the first one works fine (var résultat) but the second one (var résultat_bis), last line of code doesn't work : I get

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

What should I do to make it work? Yours sincerely Loïc

loic_midy
  • 103
  • 4

1 Answers1

0

You only need:

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

basically with Series.ne + Series.astype we create a series with 1 where Sex does not equal Female and 0 where it equals Female. Then we add 1 to this series, then it only remains to multiply and add the corresponding series

I recommend you see: When should I ever want use apply and Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

ansev
  • 30,322
  • 5
  • 17
  • 31