NumPy数组上项目的坐标 [英] Coordinates of item on NumPy array
问题描述
我有一个NumPy数组:
I have a NumPy array:
[[ 0. 1. 2. 3. 4.]
[ 7. 8. 9. 10. 4.]
[ 14. 15. 16. 17. 4.]
[ 1. 20. 21. 22. 23.]
[ 27. 28. 1. 20. 29.]]
我想快速找到特定值的坐标并避免数组上的Python循环.例如,数字4
处于打开状态:
which I want to quickly find the coordinates of specific values and avoid Python loops on the array. For example the number 4
is on:
row 0 and col 4
row 1 and col 4
row 2 and col 4
和搜索功能应返回一个元组:
and a search function should return a tuple:
((0,4),(1,4),(2,4))
这可以直接通过NunmPy的函数完成吗?
Can this be done directly via NunmPy's functions?
推荐答案
如果a
是您的数组,则可以使用:
If a
is your array, then you could use:
ii = np.nonzero(a == 4)
或
ii = np.where(a == 4)
如果您真的想要一个元组,则可以从数组的元组转换为元组的元组,但是numpy函数的返回值可以方便地在数组上执行其他操作.
If you really want a tuple, you can convert from the tuple of arrays to the tuple of tuples, but the return value from the numpy functions is convient for then doing other operations on your array.
根据OP的规范转换为元组:
Conversion to a tuple for the OP's specification:
tuple(zip(*ii))
这篇关于NumPy数组上项目的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!