0

I have a dataframe that has two columns:

df

enter image description here

There are some scientific values like 0E-10, I want create a new column such that:

df["new_col"]=df["fruits_ratio"]/(df["fruits_ratio"]+df["vegetables_ratio"])

But it give me an error like this: DivisionByZero: [<class 'decimal.DivisionByZero'>]

Is there a way to either replace the 0-E10 values or how can I avoid the error?

Thanks

yaho cho
  • 1,779
  • 1
  • 7
  • 19
user9463814
  • 199
  • 11
  • 1
    Possible duplicate of [How to deal with "divide by zero" with pandas dataframes when manipulating columns?](https://stackoverflow.com/questions/38886512/how-to-deal-with-divide-by-zero-with-pandas-dataframes-when-manipulating-colum) – Ankur Sinha Jul 26 '19 at 15:47

3 Answers3

2

I think the float function will fix this for you float(). Assign the entire column as floats since most are already.

Chris Macaluso
  • 1,372
  • 2
  • 14
  • 33
0

Given:

df = pd.DataFrame({'a':[0,1,2,3,0,1,2,3], 'b':[0,1,0,1,1,0,1,0]})

as

   a  b
0  0  0
1  1  1
2  2  0
3  3  1
4  0  1
5  1  0
6  2  1
7  3  0

Create a mask to identify where a or b is not zero which are safe to calculate on.

mask = (df['a'] != 0) | (df['b'] != 0)

the mask

0    False
1     True
2     True
3     True
4     True
5     True
6     True
7     True

Fill the result column with NaN then overwrite the ones you can calculate:

df['c'] = pd.np.NaN
df.loc[mask, 'c'] = df['a'] / (df['a'] + df['b'])

result

   a  b         c
0  0  0       NaN
1  1  1  0.500000
2  2  0  1.000000
3  3  1  0.750000
4  0  1  0.000000
5  1  0  1.000000
6  2  1  0.666667
7  3  0  1.000000

Applied to your question:

mask = (df['fruits_ratio'] != 0) | (df['vegetables_ratio'] != 0)
df['new_col'] = pd.np.NaN
df.loc[mask, 'new_col'] = df['fruits_ratio'] / (df['fruits_ratio'] + df['vegetables_ratio'])
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
0

Note that pandas supports division by zero for columns with numeric dtype (such as float and int64) by returning a result of inf. However, for columns of object type, it raises a ZeroDivisionError exception.

See this question and answer for examples.

constantstranger
  • 9,176
  • 2
  • 5
  • 19