在numpy数组中如何找到一个值的所有坐标 [英] In Numpy array how to find all of the coordinates of a value
本文介绍了在numpy数组中如何找到一个值的所有坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果要查找所有3D数组中的最大值,该如何找到它们?
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)
:
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) }
推荐答案
组合 np.argwhere
和 np.max
(已由@AshwiniChaudhary在评论中指出)可用于查找坐标:
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)}
这篇关于在numpy数组中如何找到一个值的所有坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文