【问题标题】:Numpy only on finite entriesNumpy 仅在有限条目上
【发布时间】:2014-03-16 11:29:13
【问题描述】:

这是一个函数的简短示例。它将向量映射到向量。但是,应该忽略 NaN 或 inf 的条目。目前这对我来说看起来相当笨拙。你有什么建议吗?

from scipy import stats
import numpy as np

def p(vv):
    mask = np.isfinite(vv)
    y = np.NaN * vv
    v = vv[mask]

    y[mask] = 1/v*(stats.hmean(v)/len(v))
    return y

【问题讨论】:

  • 您对 NaN 有什么问题?您的问题是“如何处理 NaN”?你的标题不是很清楚。
  • 我只是想了解更多关于他们的信息。我认为可能有一种更优雅的结构来仅对有限条目进行操作。
  • 这可能是题外话,因为您的问题应该是关于特定问题的。例如,跑题的问题包括“没有实际问题需要解决:“我很好奇其他人是否有这样的感觉。”参见stackoverflow.com/help/dont-ask)”

标签: python numpy nan


【解决方案1】:

您可以使用 Numpy 的 isnan 函数将 NaN 值更改为零,然后按如下方式删除零:

import numpy as np

def p(vv):
    # assuming vv is your array
    # use Nympy's isnan function to replace the NaN values in the array with zero

     replace_NaN = np.isnan(vv)
     vv[replace_NaN] = 0

     # convert array vv to list
     vv_list = vv.tolist()
     new_list = []

     # loop vv_list and exclude 0 values:
      for i in vv_list:
          if i != 0:
              new.list.append(i)

      # set array vv again

      vv = np.array(new_list, dtype = 'float64')

      return vv

【讨论】:

    【解决方案2】:

    我想出了这种结构:

    from scipy import stats
    import numpy as np
    
    
    ## operate only on the valid entries of x and use the same mask on the resulting vector y
    def __f(func, x):
        mask = np.isfinite(x)
        y = np.NaN * x
        y[mask] = func(x[mask])
        return y
    
    
    # implementation of the parity function
    def __pp(x):
        return 1/x*(stats.hmean(x)/len(x))
    
    
    def pp(vv):
        return __f(__pp, vv)
    

    【讨论】:

      【解决方案3】:

      掩码数组完成此功能,并允许您根据需要指定掩码。它的 numpy 1.18 文档在这里:https://numpy.org/doc/1.18/reference/maskedarray.generic.html#what-is-a-masked-array

      在掩码数组中,计算时使用 False 掩码值,而计算时忽略 True。

      使用np.isfinite() 仅获取有限值均值的示例:

      import numpy as np
      
      # Seeding for reproducing these results
      np.random.seed(0)
      
      # Generate random data and add some non-finite values
      x = np.random.randint(0, 5, (3, 3)).astype(np.float32)
      x[1,2], x[2,1], x[2,2] = np.inf, -np.inf, np.nan
      # array([[  4.,   0.,   3.],
      #        [  3.,   3.,  inf],
      #        [  3., -inf,  nan]], dtype=float32)
      
      # Make masked array. Note the logical not of isfinite
      x_masked = np.ma.masked_array(x, mask=~np.isfinite(x))
      
      # Mean of entire masked matrix
      x_masked.mean()
      # 2.6666666666666665
      
      # Masked matrix's row means
      x_masked.mean(1)
      # masked_array(data=[2.3333333333333335, 3.0, 3.0],
      #              mask=[False, False, False],
      #        fill_value=1e+20)
      
      # Masked matrix's column means
      x_masked.mean(0)
      # masked_array(data=[3.3333333333333335, 1.5, 3.0],
      #              mask=[False, False, False],
      #        fill_value=1e+20)
      

      请注意,scipy.stats.hmean() 也适用于掩码数组。

      请注意,如果您只关心检测 NaN 并离开 infs,那么您可以使用 np.isnan() 而不是 np.isfinite()

      【讨论】:

        猜你喜欢
        • 2014-05-13
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        • 2015-12-23
        • 2021-03-17
        • 2022-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多