Numpy在多维数组中索引后将所有值设置为np.nan

pdsfdshx  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(135)

我有两个numpy数组-arr 1和arr 2。arr 2包含arr 1的索引值。arr 1的形状是(100,8,96,192),arr 2的形状是(8,96,192)。我想做的是将arr 1中的所有值设置为arr 2中索引值之后的np.nan。
对于上下文,arr 1是time x model x lat x lon,arr 2中的所有索引值都对应于arr 1数组中的一个时间点。我想将arr 1的值设置为arr 2中的时间点之后的np. nan。
样本数据

arr1 = np.random.rand(*(100, 8, 96, 192))
arr2 = np.random.randint(low=0, high=80,size=(8, 96, 192))
in: print(arr1)

out: array([[[[0.61718651, 0.24426295, 0.9165573 , ..., 0.24155022,
          0.22327592, 0.9533857 ],
         [0.21922781, 0.87948651, 0.926359  , ..., 0.64281931,
         ...,
         [0.09342961, 0.29533331, 0.11398662, ..., 0.36239606,
          0.40228814, 0.87284515]]]])
in: print(arr2)

out: array([[[22,  5, 64, ...,  0, 37,  6],
        [71, 48, 33, ...,  8, 38, 32],
        [15, 41, 61, ..., 56, 32, 48],
        ...,
        ...,
        [66, 31, 32, ...,  0, 10,  6],
        [ 9, 28, 72, ..., 71, 29, 34],
        [65, 22, 50, ..., 58, 49, 35]]])

作为参考,我以前问过这个问题,有一些相似之处。Numpy multi-dimensional index
基于此,我尝试

arr1 = np.random.rand(100, 8, 96, 192)
arr2 = np.random.randint(low=0, high=80, size=(8, 96, 192))
I, J, K = np.indices((8, 96, 192), sparse=True)
out = arr1[arr2:, I, J, K]

TypeError: only integer scalar arrays can be converted to a scalar index

另外,可能在概念上与此类似,但对于高维数组Set values in numpy array to NaN by index

t0ybt7op

t0ybt7op1#

在这种情况下,我建议使用与arr1形状相同的布尔掩码进行索引。像您上一个问题中的整数数组高级索引在这里要困难得多,因为对于每个模型x lat x lon,需要索引可变数量的元素。示例:

import numpy as np

arr1 = np.random.rand(*(100, 8, 96, 192))
arr2 = np.random.randint(low=0, high=80,size=(8, 96, 192))

# These are the possible indices along the first axis in arr1
# Hence shape (100, 1, 1, 1):
idx = np.arange(100)[:, None, None, None]

arr1[idx > arr2] = np.nan

相关问题