【发布时间】:2022-10-18 04:26:41
【问题描述】:
假设我有一个数组,例如:
a1 = np.array([.1, .2, 23., 4.3, 3.2, .1, .05, .2, .3, 4.2, 7.6])
我过滤掉并创建一个所有小于 1 的值的掩码,例如:
a2 = a1[a1 >= 1]
a2_mask = np.ma.masked_where(a1 < 1, a1)
然后搜索特定值:
a2_idx = np.where(a2==3.2)[0][0]
我如何将该索引转换为原始数组中的相应索引?
例如
>>> a2_idx
2
>>> a1_idx = reframe_index(a2_idx, a2_mask)
>>> a1_idx
4
我天真的实现是:
def reframe_index(old_idx, mask):
cnt = 0
ref = 0
for v in mask:
if not isinstance(v, (int, float)):
cnt += 1
else:
if ref == old_idx:
return ref + cnt
ref += 1
Numpy 是否有更有效的方法来做到这一点?
【问题讨论】: