convert nan value to zero

前端 未结 9 982
暖寄归人
暖寄归人 2020-11-30 23:28

I have a 2D numpy array. Some of the values in this array are NaN. I want to perform certain operations using this array. For example consider the array:

<
相关标签:
9条回答
  • 2020-12-01 00:08

    nan is never equal to nan

    if z!=z:z=0
    

    so for a 2D array

    for entry in nparr:
        if entry!=entry:entry=0
    
    0 讨论(0)
  • 2020-12-01 00:10

    Where A is your 2D array:

    import numpy as np
    A[np.isnan(A)] = 0
    

    The function isnan produces a bool array indicating where the NaN values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.

    0 讨论(0)
  • 2020-12-01 00:22

    For your purposes, if all the items are stored as str and you just use sorted as you are using and then check for the first element and replace it with '0'

    >>> l1 = ['88','NaN','67','89','81']
    >>> n = sorted(l1,reverse=True)
    ['NaN', '89', '88', '81', '67']
    >>> import math
    >>> if math.isnan(float(n[0])):
    ...     n[0] = '0'
    ... 
    >>> n
    ['0', '89', '88', '81', '67']
    
    0 讨论(0)
  • 2020-12-01 00:25

    How about nan_to_num()?

    0 讨论(0)
  • 2020-12-01 00:26

    A code example for drake's answer to use nan_to_num:

    >>> import numpy as np
    >>> A = np.array([[1, 2, 3], [0, 3, np.NaN]])
    >>> A = np.nan_to_num(A)
    >>> A
    array([[ 1.,  2.,  3.],
           [ 0.,  3.,  0.]])
    
    0 讨论(0)
  • 2020-12-01 00:32

    This should work:

    from numpy import *
    
    a = array([[1, 2, 3], [0, 3, NaN]])
    where_are_NaNs = isnan(a)
    a[where_are_NaNs] = 0
    

    In the above case where_are_NaNs is:

    In [12]: where_are_NaNs
    Out[12]: 
    array([[False, False, False],
           [False, False,  True]], dtype=bool)
    
    0 讨论(0)
提交回复
热议问题