【问题标题】:Iterate over the output of `np.where`迭代 `np.where` 的输出
【发布时间】:2014-03-20 04:13:32
【问题描述】:

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

一种方法是:

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

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

【问题讨论】:

    标签: python numpy multidimensional-array indexing


    【解决方案1】:

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

    【讨论】:

    • * 有什么意义?
    • * 是splat or unpack operator。由于np.where 返回一个numpy 数组的奇异元组,* 允许我们将每个元组元素作为位置参数传递给zip。请注意,对于 Python3,zip 返回一个生成器,因此如果不直接对其进行迭代请小心(您可能需要使用list(zip(...)))。
    • 感谢您的解释。当我使用 python 3 运行它时,我真的很困惑。你的回答澄清了这个异常。
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 2021-04-22
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 2019-03-29
      • 2014-03-06
      • 1970-01-01
      相关资源
      最近更新 更多