【问题标题】:In Numpy array how to find all of the coordinates of a value在 Numpy 数组中如何找到一个值的所有坐标
【发布时间】:2017-01-02 23:37:50
【问题描述】:

如果我想找到所有坐标,如何找到 3D 数组中最大值的坐标?

到目前为止,这是我的代码,但它不起作用,我不明白为什么。

s = set()
elements = np.isnan(table)
numbers = table[~elements]
biggest = float(np.amax(numbers))
a = table.tolist()
for x in a:
    coordnates = np.argwhere(table == x)
    if x == biggest:
        s.add((tuple(coordinates[0]))
print(s)

例如:

table = np.array([[[ 1, 2, 3],
        [ 8, 4, 11]],

        [[ 1, 4, 4],
        [ 8, 5, 9]],

        [[ 3, 8, 6],
        [ 11, 9, 8]],

        [[ 3, 7, 6],
        [ 9, 3, 7]]])

应该返回s = {(0, 1, 2),(2, 1, 0)}

【问题讨论】:

  • 有理由不使用 Numpy 吗?
  • 我尝试使用 Numpy,只是没有找到可以返回所有坐标的特定函数,有吗?
  • np.argwhere(table == table.max()) 返回array([[0, 1, 2], [2, 1, 0]])
  • 使用numpy.nanmax 忽略Nans:np.argwhere(table == np.nanmax(table))

标签: python arrays numpy multidimensional-array


【解决方案1】:

结合np.argwherenp.max(正如@AshwiniChaudhary 在 cmets 中已经指出的那样)可用于查找坐标:

>>> np.argwhere(table == np.max(table))
array([[0, 1, 2],
       [2, 1, 0]], dtype=int64)

要获得一个集合,您可以使用集合理解(需要将子数组转换为元组,以便将它们存储在集合中):

>>> {tuple(coords) for coords in np.argwhere(table == np.max(table))}
{(0, 1, 2), (2, 1, 0)}

【讨论】:

    【解决方案2】:
    In [193]: np.max(table)
    Out[193]: 11
    In [194]: table==np.max(table)
    Out[194]: 
    array([[[False, False, False],
            [False, False,  True]],
      ...
           [[False, False, False],
            [False, False, False]]], dtype=bool)
    In [195]: np.where(table==np.max(table))
    Out[195]: 
    (array([0, 2], dtype=int32),
     array([1, 1], dtype=int32),
     array([2, 0], dtype=int32))
    

    transpose 将这个由 3 个数组组成的元组变成具有 2 组坐标的数组:

    In [197]: np.transpose(np.where(table==np.max(table)))
    Out[197]: 
    array([[0, 1, 2],
           [2, 1, 0]], dtype=int32)
    

    这个操作很常见,它已经被包装在一个函数调用中(查看它的文档)

    In [199]: np.argwhere(table==np.max(table))
    Out[199]: 
    array([[0, 1, 2],
           [2, 1, 0]], dtype=int32)
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多