J  C
J C

Reputation: 11

Python: When would 0.0/0.0 =NaN or inf , when would it gives exception?

I got a dataframe in python.pandas:

q   v         k
0   0   
16  42 
14  59 
... ...

Now I want let k=q/v if v!=0 else k=0. This is how I did:

>>>df['k'] = df['q'].astype(float16) /df['v'].astype(float16)
q  v    k
0  0  NaN
>>>df['k'][df['v']==0] = 0.0

When set float16, it gives NaN. However

>>>0/np.float64(0) 
nan
>>>df['k'] = df['q'] /df['v'].astype(float16)
ZeroDivisionError

Moreover,

>>> df['k'] = df['q'].astype(int16)/df['v'].astype(int16)
q  v    k
0  0  inf
>>> np.int64(0)/np.int64(0)
nan

Why?

Upvotes: 1

Views: 353

Answers (1)

JAB
JAB

Reputation: 12801

you can use this for a one liner:

df =pd.DataFrame({'q':[0,16,14],'v':[0,42,59]})
df.astype('float64')
df['k']=(df.q/df.v).replace({ np.inf : 0 })

Numpy is handling the divide by zero error. (The behavior can be changed using sterr http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html#numpy.seterr)

Here is a post that show a function on handling it in pure python: How to get Python division by -0.0 and 0.0 to result in -Inf and Inf, respectively?

Upvotes: 2

Related Questions