【问题标题】:How to get indices of a 2D array from index of the masked array如何从掩码数组的索引中获取二维数组的索引
【发布时间】:2019-01-06 16:21:06
【问题描述】:

我需要一个 2D 数组的原始索引在一个循环中覆盖一个屏蔽数组的索引。我试试:

for i in range(Arr[mask].size):
    tmp = numpy.zeros(mask.shape, dtype=bool)
    tmp[mask][i] = True
    j,k = numpy.where(tmp)
    ...

不幸的是,最后一行返回

(array([], dtype=int64), array([], dtype=int64))   

找到j和k的好方法是什么?

【问题讨论】:

  • 使用布尔索引 tmp[mask][i] = 不会修改 tmptmp[mask] 是一个副本。 where 是准确的 - tmp 中没有任何 True 值。

标签: numpy indexing mask


【解决方案1】:

因为它是一个二维数组,你可以简单地遍历掩码而不是遍历掩码数组:

for j, k in zip(*np.where(mask)):
    value = Arr[j,k]
    # ...

如果您还想获取当前(屏蔽)值的编号:

for i, (j, k) in enumerate(zip(*np.where(mask))):
    value = Arr[j,k]
    # ...

【讨论】:

  • 行得通!谢谢!此外,我使用“for i, (j, k) in enumerate(zip(*np.where(mask)))” 来获取索引“i”
  • np.transpose(np.where(...) 产生一个索引对数组。 np.argwhere 做同样的事情。 zip(*...) 是一个列表转置。
猜你喜欢
  • 2022-10-25
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 2022-07-27
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
相关资源
最近更新 更多