mardi 17 avril 2018

How to perform a calculation with conditionals in pandas?

I am trying to write a conditional where I want to get the average cost per visit in a new column. However, if the visit count is 0, then I want to use '1' instead so that the Visit_cost is not infinity.

My approach is throwing an error:

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

df

id    Cost          Visit
2     52            1
3     85            0
4     853           10

df['VISIT_COST'] = [df['Cost']/df['Visit'] if df['Visit'] != 0 else df['Cost']/1]

final df:

id    Cost          Visit    VISIT_COST
2     52            1        52
3     85            0        85
4     853           10       85.3

Aucun commentaire:

Enregistrer un commentaire