Numpy - 从形状和索引中获取掩码
Numpy - get mask from shape and indices
使用 np.instersect1d
后,我检索了我想要检索的索引。我想将这些索引变成一个遮罩,这样我就可以将它与另一个遮罩结合起来。
我要的是:
>>> times_1.shape
... (160,)
>>> _, time_indices, _ = np.intersect1d(times_1, times_2, return_indices=True)
>>> time_indices.shape
... (145,)
# Some way to turn return mask from original shape and indices
>>> time_mask = get_mask_from_shape(time_1.shape, time_indices)
>>> time_mask.shape
... (160,)
实现功能 get_mask_from_shape
的最简单方法是什么?
如果我的想法正确,我会应用这个模式我一直在寻找 :
intersection = np.intersect1d(times_1, times_2)
intersection = np.sort(intersection)
locations = np.searchsorted(intersection, times_1)
locations[locations==len(intersection)] = 0
time_mask = intersection[locations]==times_1
根据 numpy
documentation.,searchsorted
方法查找应将 times_1
的元素插入到 intersection
中以维持顺序的索引
我找到的解决方案是:
time_mask = np.zeros(times_1.shape, dtype=bool)
time_mask[time_indices] = True
使用 np.instersect1d
后,我检索了我想要检索的索引。我想将这些索引变成一个遮罩,这样我就可以将它与另一个遮罩结合起来。
我要的是:
>>> times_1.shape
... (160,)
>>> _, time_indices, _ = np.intersect1d(times_1, times_2, return_indices=True)
>>> time_indices.shape
... (145,)
# Some way to turn return mask from original shape and indices
>>> time_mask = get_mask_from_shape(time_1.shape, time_indices)
>>> time_mask.shape
... (160,)
实现功能 get_mask_from_shape
的最简单方法是什么?
如果我的想法正确,我会应用这个模式我一直在寻找
intersection = np.intersect1d(times_1, times_2)
intersection = np.sort(intersection)
locations = np.searchsorted(intersection, times_1)
locations[locations==len(intersection)] = 0
time_mask = intersection[locations]==times_1
根据 numpy
documentation.,searchsorted
方法查找应将 times_1
的元素插入到 intersection
中以维持顺序的索引
我找到的解决方案是:
time_mask = np.zeros(times_1.shape, dtype=bool)
time_mask[time_indices] = True