迭代`np.where`的输出 [英] Iterate over the output of `np.where`

查看:583
本文介绍了迭代`np.where`的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a 3D array and use np.where to find elements that meet a certain condition. The output of np.where is a tuple of three 1D arrays, each giving the indices along a single axis. I'd like to iterate over this output and print out the index of each point in the matrix that met the condition.

一种方法是:

indices = np.where(myarray == 0)
for i in range(0, len(indices[0])):
    print indices[0][i], indices[1][i], indices[2][i]

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

However, it looks a bit cumbersome and I was wondering if there's a better way?

推荐答案

使用 zip

indices = zip(*np.where(myarray == 0))

然后你可以做到

for i, j, k in indices:
    print ...

例如,

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)]

这篇关于迭代`np.where`的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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