首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迭代`np.where`的输出

迭代`np.where`的输出
EN

Stack Overflow用户
提问于 2014-02-19 16:56:48
回答 2查看 10.4K关注 0票数 8

我有一个3D数组,并使用np.where查找满足特定条件的元素。np.where的输出是由三个一维数组组成的元组,每个数组沿一个轴给出索引。我想迭代这个输出,并打印出矩阵中满足条件的每个点的索引。

这样做的一种方法是:

代码语言:javascript
复制
indices = np.where(myarray == 0)
for i in range(0, len(indices[0])):
    print indices[0][i], indices[1][i], indices[2][i]

然而,它看起来有点麻烦,我想知道是否有更好的方法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-19 17:00:47

使用zip

代码语言:javascript
复制
indices = zip(*np.where(myarray == 0))

那你就可以

代码语言:javascript
复制
for i, j, k in indices:
    print ...

例如,

代码语言:javascript
复制
In [1]: x = np.random_integers(0, 1, (3, 3, 3))
In [2]: np.where(x) # you want np.where(x==0)
Out[2]: (array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2]),
         array([0, 1, 1, 2, 2, 0, 0, 1, 1, 2]),
         array([1, 0, 1, 0, 1, 1, 2, 0, 2, 2]))
In [3]: zip(*np.where(x))
Out[3]: [(0, 0, 1),
         (0, 1, 0),
         (0, 1, 1),
         (0, 2, 0),
         (0, 2, 1),
         (1, 0, 1),
         (1, 0, 2),
         (1, 1, 0),
         (1, 1, 2),
         (2, 2, 2)]
票数 9
EN

Stack Overflow用户

发布于 2014-08-13 15:59:34

使用np.transpose优于zip,对于大型数组来说更快

代码语言:javascript
复制
import numpy as np
myarray = np.random.randint(0, 7, size=1000000)
%timeit indices = zip(*np.where(myarray == 0))
%timeit indices = np.transpose(np.where(myarray == 0))

10 loops, best of 3: 31.8 ms per loop
100 loops, best of 3: 15.9 ms per loop
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21887138

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档