我经常使用 numpy.where 函数来收集具有某些属性的矩阵的索引元组。例如
import numpy as np
X = np.random.rand(3,3)
>>> X
array([[ 0.51035326, 0.41536004, 0.37821622],
[ 0.32285063, 0.29847402, 0.82969935],
[ 0.74340225, 0.51553363, 0.22528989]])
>>> ix = np.where(X > 0.5)
>>> ix
(array([0, 1, 2, 2]), array([0, 2, 0, 1]))
ix 现在是包含行和列索引的 ndarray 对象的元组,而子表达式 X>0.5 包含一个布尔矩阵,指示哪些单元格具有 >0.5 属性。每种表示方式都有其自身的优势。
获取 ix 对象并稍后在需要时将其转换回布尔形式的最佳方法是什么?例如
G = np.zeros(X.shape,dtype=np.bool)
>>> G[ix] = True
有没有完成同样事情的单线?