【问题标题】:How I can i conditionally change the values in a numpy array taking into account nan numbers?考虑到 nan 数字,我如何有条件地更改 numpy 数组中的值?
【发布时间】:2012-09-07 15:16:50
【问题描述】:

我的数组是一个二维矩阵,除了负值和正值之外,它还有 numpy.nan 值:

>>> array
array([[        nan,         nan,         nan, ..., -0.04891211,
            nan,         nan],
   [        nan,         nan,         nan, ...,         nan,
            nan,         nan],
   [        nan,         nan,         nan, ...,         nan,
            nan,         nan],
   ..., 
   [-0.02510989, -0.02520096, -0.02669156, ...,         nan,
            nan,         nan],
   [-0.02725595, -0.02715945, -0.0286231 , ...,         nan,
            nan,         nan],
   [        nan,         nan,         nan, ...,         nan,
            nan,         nan]], dtype=float32)

我想用一个数字替换所有正数,用另一个数字替换所有负数。

如何使用 python/numpy 执行该操作?

(为了记录,矩阵是geoimage的结果,我想对其进行分类)

【问题讨论】:

  • 数组中有正数,只是没有显示在预览中

标签: python open-source numpy statistics gdal


【解决方案1】:

试试:

a[a>0] = 1
a[a<0] = -1

【讨论】:

    【解决方案2】:

    您的数组中有np.nan 的事实应该无关紧要。只需使用花哨的索引:

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

    如果你想替换你的np.nans:

    x[np.isnan(x)] = something_not_nan
    

    有关花式索引 a tutorialNumPy documentation 的更多信息。

    【讨论】:

    • 如果有一个单一的转换会更好,因为如果你的方法不起作用,例如new_value_for_pos &lt; 0.
    【解决方案3】:

    然后对当前值进行加减(np.nan 不受影响)

    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)
    

    输出

    [[-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]]
    

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 2021-08-26
      • 2013-06-04
      • 2017-06-25
      • 1970-01-01
      • 2020-06-14
      • 2019-07-05
      • 1970-01-01
      相关资源
      最近更新 更多