How I can i conditionally change the values in a numpy array taking into account nan numbers?

前端 未结 3 1287
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-02 13:56

My array is a 2D matrix and it has numpy.nan values besides negative and positive values:

>>> array
array([[        nan,         nan,         nan, ...,         


        
3条回答
  •  礼貌的吻别
    2021-02-02 14:24

    to add or subtract to current value then (np.nan not affected)

    import numpy as np
    
    a = np.arange(-10, 10).reshape((4, 5))
    
    print("after -")
    print(a)
    
    a[a<0] = a[a<0] - 2
    a[a>0] = a[a>0] + 2
    
    
    print(a)
    

    output

    [[-10  -9  -8  -7  -6]
     [ -5  -4  -3  -2  -1]
     [  0   1   2   3   4]
     [  5   6   7   8   9]]
    
    after -
    
    [[-12 -11 -10  -9  -8]
     [ -7  -6  -5  -4  -3]
     [  0   3   4   5   6]
     [  7   8   9  10  11]]
    

提交回复
热议问题