假设我有下面的numpy数组
>>> arr = np.array([[0,1,0,1],
[0,0,0,1],
[1,0,1,0]])
其中0
值表示“有效”值,1
值表示“无效”值。接下来,假设我筛选出无效的1
值如下:
>>> mask = arr == 1
>>> arr_filt = arr[~mask]
array([0, 0, 0, 0, 0, 0, 0])
如果我想从原始arr
中的有效值的线性索引(arr
)转到新过滤的arr_filt
中相同值的线性索引,则可以进行如下操作:
# record the cumulative total number of invalid values
num_invalid_prev = np.cumsum(mask.flatten())
# example of going from the linear index of a valid value in the
# original array to the linear index of the same value in the
# filtered array
ij_idx = (0,2)
linear_idx_orig = np.ravel_multi_index(ij_idx,arr.shape)
linear_idx_filt = linear_idx_orig - num_invalid_prev[linear_idx_orig]
不过,我有兴趣走另一条路。也就是说,给定过滤后的arr_filt
中的有效值的线性索引和相同的num_invalid_prev
数组,我可以在未过滤的arr
中返回相同有效值的线性索引吗?
发布于 2022-08-02 03:17:41
您可以使用np.nonzero()
获取索引:
ix = np.c_[np.nonzero(~mask)]
>>> ix
array([[0, 0],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 1],
[2, 3]])
然后,您可以查找第二个有效值的索引:
>>> tuple(ix[1])
(0, 2)
>>> arr[tuple(ix[1])]
0
https://stackoverflow.com/questions/73200656
复制相似问题