使用 numpy trapz 集成时跳过 NaN 值

问题描述 投票:0回答:1

我正在使用 numpy 函数

trapz
来执行积分。我的一些数组具有
NaN
值,我希望梯形算法在计算梯形时简单地“跳过”这些值,而不是为该切片返回
NaN
。有没有一种简单的方法可以实现这一点?我查看了 scipy 的
trapz
函数,它似乎也无法做到这一点。

python numpy scipy nan numerical-integration
1个回答
0
投票

按照评论中的建议,您可以创建一个 屏蔽数组,其中屏蔽掉 NaN 元素,并在屏蔽数组上使用

trapz

import numpy as np
rng = np.random.default_rng(3825983453)

# generate data with NaN element
y = rng.random(20)
y[0] = np.nan

# integrate without the NaN
ref = np.trapz(y[1:])

# mask the NaN and integrate the whole array
y_masked = np.ma.masked_invalid(y)
res = np.trapz(y_masked)

# results are identical
np.testing.assert_equal(res, ref)

(我认为这应该写成对后代的明确答案)。

© www.soinside.com 2019 - 2024. All rights reserved.