如何反转numpy.where(np.where)函数

Set*_*jmp 5 python boolean numpy where indices

我经常使用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]))
Run Code Online (Sandbox Code Playgroud)

ix现在是包含行索引和列索引的ndarray对象的元组,而子表达式X> 0.5包含一个布尔矩阵,指示哪些单元格具有> 0.5属性.每种表示都有其自身的优点.

获取ix对象并在以后需要时将其转换回布尔形式的最佳方法是什么?例如

G = np.zeros(X.shape,dtype=np.bool)
>>> G[ix] = True
Run Code Online (Sandbox Code Playgroud)

是否有一个单行程完成同样的事情?

Bi *_*ico 5

这样的事可能吗?

mask = np.zeros(X.shape, dtype='bool')
mask[ix] = True
Run Code Online (Sandbox Code Playgroud)

但如果它是一个简单的东西X > 0,你可能会做得更好,mask = X > 0除非mask非常稀疏或你不再有参考X.