如何反转numpy.where(np.where)函数 [英] How to invert numpy.where (np.where) function

查看:381
本文介绍了如何反转numpy.where(np.where)函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用numpy.where函数来收集具有某些属性的矩阵的索引元组.例如

I frequently use the numpy.where function to gather a tuple of indices of a matrix having some property. For example

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 is now a tuple of ndarray objects that contain the row and column indices, whereas the sub-expression X>0.5 contains a single boolean matrix indicating which cells had the >0.5 property. Each representation has its own advantages.

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

What is the best way to take ix object and convert it back to the boolean form later when it is desired? For example

G = np.zeros(X.shape,dtype=np.bool)
>>> G[ix] = True

是否有可以完成同一件事的单缸纸?

Is there a one-liner that accomplishes the same thing?

推荐答案

像这样的事情?

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

,但是如果它像X > 0这样简单,则最好执行mask = X > 0,除非mask非常稀疏或不再引用X.

but if it's something simple like X > 0, you're probably better off doing mask = X > 0 unless mask is very sparse or you no longer have a reference to X.

这篇关于如何反转numpy.where(np.where)函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆