【问题标题】:How to get a value of numpy ndarray at index or NaN for IndexError?如何获取索引处的numpy ndarray值或IndexError的NaN?
【发布时间】:2019-02-15 10:39:37
【问题描述】:

我的问题和这个类似

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])

【问题讨论】:

  • 我的回答能解决你的问题吗?如果是这样,您能否将其标记为已接受?

标签: python numpy numpy-ndarray


【解决方案1】:

鉴于我们的数据

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])

【讨论】:

    猜你喜欢
    • 2018-02-16
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多