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

前端 未结 3 1288
佛祖请我去吃肉
佛祖请我去吃肉 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:19

    The fact that you have np.nan in your array should not matter. Just use fancy indexing:

    x[x>0] = new_value_for_pos
    x[x<0] = new_value_for_neg
    

    If you want to replace your np.nans:

    x[np.isnan(x)] = something_not_nan
    

    More info on fancy indexing a tutorial and the NumPy documentation.

    0 讨论(0)
  • 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]]
    
    0 讨论(0)
  • 2021-02-02 14:39

    Try:

    a[a>0] = 1
    a[a<0] = -1
    
    0 讨论(0)
提交回复
热议问题