mardi 30 novembre 2021

Issues with "if-else" statement

I have the following dataframe:

df = pd.DataFrame({'y': [4,3,6,1], 'x': [0,0,2,1]})

I would like to compute the ratio of the two columns. However, since there are some 0 in the denominator, I would like to fix if with a if else statement. The condition should be: if in the denominator there is 0, replace it with 1 and compute the ratio, otherwise as usual.

I did this (and other variations) but it doesn't work (see below error):

if df['x'] == 0:
   df['x'] = 1
   df['ratio'] = df['y']/df['x']
else:
   df['ratio'] = df['y']/df['x']

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

Can anyone help me?

Thanks!

Aucun commentaire:

Enregistrer un commentaire