0

I want to create a new column based on a division of two different columns, but make sure that I do not divide by 0, if the price is 0 set it to none.

if I try to just divide I get 'inf' where the price is 0:

df['new'] = df['memory'] / df['price']

        id  memory    price
0        0    7568   751.64
1        1   53759   885.17
2        2   41140  1067.78
3        3   10558        0
4        4   44436  1023.13

I didn't find a way to add condition

Aviv Moyal
  • 17
  • 4

1 Answers1

1

To avoid division by zero, I would avoid dividing the values by zero. Please take a look at the following example.

I hope this helps.

Best regards

import pandas as pd

data = {'id': [0, 1, 2, 3, 4], 'memory': [7568, 53759, 41140, 10558, 44436], 'price': [751.64, 885.17, 1067.78, 0, 1023.13]}
df = pd.DataFrame(data)

# adding a new column and setting the values to "none"
df['new'] = "none"

for i in range(len(df)):
    if df.iat[i,2] != 0:
        df.iat[i, 3] = df.iat[i, 1] / df.iat[i, 2]
        
print(df)

enter image description here