Numpy only on finite entries

好久不见. 提交于 2019-12-25 16:49:09

问题


Here's a brief example of a function. It maps a vector to a vector. However, entries that are NaN or inf should be ignored. Currently this looks rather clumsy to me. Do you have any suggestions?

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

回答1:


I have came up with this kind of construction:

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)



回答2:


You can change the NaN values to zero with Numpy's isnan function and then remove the zeros as follows:

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


来源:https://stackoverflow.com/questions/21824499/numpy-only-on-finite-entries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!