仅在有限项上为小数 [英] Numpy only on finite entries

查看:90
本文介绍了仅在有限项上为小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

我想出了这种构造:

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)

这篇关于仅在有限项上为小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆