Handling division by zero in Pandas calculations

后端 未结 3 467
情书的邮戳
情书的邮戳 2021-01-05 16:31

I have the following data:

a = pd.Series([1, 2, 3])
b = pd.Series([0, 0, 0])

If there is a division by zero I want to in some cases

相关标签:
3条回答
  • 2021-01-05 17:05

    I think you can use Series.replace:

    print (a.div(b.replace(0, np.nan)).fillna(0))
    0    0.0
    1    0.0
    2    0.0
    dtype: float64
    
    print (a.div(b.replace(0, np.nan)).fillna(a))
    0    1.0
    1    2.0
    2    3.0
    dtype: float64
    
    0 讨论(0)
  • 2021-01-05 17:06

    You can use df.replace after division:

    (a / b).replace(np.inf, 0)
    
    0    0.0
    1    0.0
    2    0.0
    dtype: float64
    
    (a / b).replace(np.inf, a)
    
    0    1.0
    1    2.0
    2    3.0
    dtype: float64
    

    Want to handle negative infinity too? You'll need:

    (a / b).replace((np.inf, -np.inf), (a, a))
    
    0 讨论(0)
  • 2021-01-05 17:17

    You can also use the np.isinf function to check for infinite values and then substitue them with 0. Ex-

    a = np.asarray(np.arange(5))
    b = np.asarray([1,2,0,1,0])
    
    c = a/b
    c[np.isinf(c)] = 0
    
    #result
    >>> c
    array([ 0. ,  0.5,  0. ,  3. ,  0. ])
    
    0 讨论(0)
提交回复
热议问题