【问题标题】:Python Numpy 2-dimensional array iterationPython Numpy 二维数组迭代
【发布时间】:2011-12-28 20:42:12
【问题描述】:

希望将索引列表构建到二维 bool_ 数组中,其中 True。

import numpy
arr = numpy.zeros((6,6), numpy.bool_)
arr[2,3] = True
arr[5,1] = True
results1 = [[(x,y) for (y,cell) in enumerate(arr[x].flat) if cell] for x in xrange(6)]
results2 = [(x,y) for (y,cell) in enumerate(arr[x].flat) if cell for x in xrange(6)]

结果 1:

[[], [], [(2, 3)], [], [], [(5, 1)]]

结果 2 完全错误

目标:

[(2, 3),(5, 1)]

有什么方法可以做到这一点而无需事后将列表变平,或者有什么更好的方法来做到这一点?

【问题讨论】:

    标签: python arrays numpy iterator


    【解决方案1】:

    我认为您正在寻找的功能是numpy.where。这是一个例子:

    >>> import numpy
    >>> arr = numpy.zeros((6,6), numpy.bool_)
    >>> arr[2,3] = True
    >>> arr[5,1] = True
    >>> numpy.where(arr)
    (array([2, 5]), array([3, 1]))
    

    你可以把它变成这样的索引:

    >>> numpy.array(numpy.where(arr)).T
    array([[2, 3],
           [5, 1]])
    

    【讨论】:

    • 天哪,没听说过。 zip(*numpy.where(arr)) 运行良好。我会让这个开放一段时间,看看是否有其他人有替代方案。
    • np.where() 与单个参数等效于np.nonzero()。转换为 OP 的格式:np.transpose(np.nonzero(a)),相当于np.argwhere(a)
    【解决方案2】:
    >>> import numpy as np
    >>> arr = np.zeros((6,6), np.bool_)
    >>> arr[2,3] = True
    >>> arr[5,1] = True
    >>> np.argwhere(arr)
    array([[2, 3],
           [5, 1]])
    

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 2015-04-04
      • 2018-12-01
      • 2016-01-28
      • 1970-01-01
      • 2014-01-31
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多