如何在 IndexError 的索引或 NaN 处获取 numpy ndarray 的值?

How to get a value of numpy ndarray at index or NaN for IndexError?

我的问题和这个类似

Get value at list/array index or "None" if out of range in Python

但我想使用多维 numpy 数组。

是否可以在不事先检查索引的情况下完成此操作?

data = np.ones((2,3,4))
idx1 = [0,1]
idx2 = [1,2]
idx3 = [0, 100]
data[idx1, idx2, idx3]

期望的输出:

array([1., np.nan])

根据我们的数据

import numpy as np    
data = np.ones((2,3,4))
idx = [[0,1], [1,2], [0, 100]]
shape = np.array(data.shape)

您可以使用

获取超出原始数组的任何索引列
invalids = np.any(idx > shape[:, None] - 1, axis=0)

并使用

将您的索引裁剪为有效值
valids = np.clip(idx, 0, shape[:, None] - 1)

这些指标可以用来索引我们的数组

out = data[valids.tolist()]

无效索引的掩码可用于将异常值设置为nan

out[invalids] = np.nan
# array([ 1., nan])