7

我经常使用 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

有没有完成同样事情的单线?

4

3 回答 3

9

可能是这样的?

mask = np.zeros(X.shape, dtype='bool')
mask[ix] = True

X > 0如果mask = X > 0它像.maskX

于 2012-02-29T17:55:23.743 回答
3

文档字符串的底部np.where建议np.in1d用于此目的。

>>> x = np.array([1, 3, 4, 1, 2, 7, 6])
>>> indices = np.where(x % 3 == 1)[0]
>>> indices
array([0, 2, 3, 5])
>>> np.in1d(np.arange(len(x)), indices)
array([ True, False,  True,  True, False,  True, False], dtype=bool)

(虽然这是一个不错的单线,但它比@Bi Rico 的解决方案慢得多。)

于 2014-09-05T11:31:42.970 回答
2
mask = X > 0
imask = np.logical_not(mask)

例如

编辑:抱歉之前这么简洁。不应该在电话上回答问题:P

正如我在示例中所指出的,最好只反转布尔掩码。比从where.

于 2012-02-29T20:04:00.177 回答