Numpy仅限于有限条目

时间:2014-02-17 08:52:41

标签: python numpy nan

这是一个功能的简短示例。它将矢量映射到矢量。但是,应忽略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

3 个答案:

答案 0 :(得分:1)

我想出了这种结构:

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)

答案 1 :(得分:1)

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

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

使用this. transaccion = trans;仅获取有限值的平均值的示例:

this. transaccion = transaccion;

请注意,np.isfinite()也适用于掩码数组。

请注意,如果您关心的只是检测NaN并留下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()而不是inf

答案 2 :(得分:0)

您可以使用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