我有两个 numpy 数组——arr1 和 arr2。 arr2 包含 arr1 的索引值。 arr1的形状是(100, 8, 96, 192),arr2的形状是(8, 96, 192)。我想做的是在 arr2 中的索引值之后将 arr1 中的所有值设置为 np.nan。
对于上下文,arr1 是时间 x 模型 x 纬度 x lon 并且 arr2 中的所有索引值对应于 arr1 数组中的时间点。我想将 arr2 中的时间点之后的 arr1 值设置为 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 多维索引
基于此,我尝试了
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
此外,也许在概念上与此类似,但对于更高维的数组 通过索引将 numpy 数组中的值设置为 NaN
在这种情况下,我建议使用与
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