In Numpy array how to find all of the coordinates of a value

浪子不回头ぞ 提交于 2020-08-08 05:11:46

问题


How do i find the coordinates of the biggest value in a 3D array if I want to find all of them?

This is my code so far, but it doesnt work, I fail to understand why.

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)

for example:

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

Should return s = {(0, 1, 2),(2, 1, 0)}


回答1:


Combining np.argwhere and np.max (as already pointed out by @AshwiniChaudhary in the comments) can be used to find the coordinates:

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

To get a set, you can use a set-comprehension (one needs to convert the subarrays to tuples so they can be stored in the set):

>>> {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 turns this tuple of 3 arrays into an array with 2 sets of coordinates:

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

This operation is common enough that it has been wrapped in a function call (look at its docs)

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


来源:https://stackoverflow.com/questions/41434586/in-numpy-array-how-to-find-all-of-the-coordinates-of-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!