Reputation: 53
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)}
Upvotes: 2
Views: 3136
Reputation: 231335
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)
Upvotes: 0
Reputation: 152587
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)}
Upvotes: 1