[英]The most efficient way of finding indices of element(s) in numpy 2D array
Out of huge matrix in numpy (currently 1000x1000
) only a few elements are relevant for me.在 numpy(当前
1000x1000
)的巨大矩阵中,只有少数元素与我相关。 Say these elements are >1000
in value and others are way lower.假设这些元素的价值
>1000
,而其他元素的价值要低得多。 I need to find indices of all such elements in the most efficient way because the search will be repeated often and the matrix can become even bigger.我需要以最有效的方式找到所有这些元素的索引,因为搜索会经常重复并且矩阵会变得更大。
For now I have two different approaches which should be about the same complexity (I omit possible solutions with for
as inefficient):现在我有两种不同的方法,它们的复杂性应该大致相同(我省略了效率低下的可能解决
for
):
import numpy as np
A = np.zeros((1000,1000))
#do something with the matrix
#first solution with np.where
np.where(A > 999).T
# array([[0, 0],[1, 20]....[785, 445]], dtype=int64) - made up numbers
#another solution with np.argwhere
np.argwhere(A > 999)
# array([[0, 0],[1, 20]....[785, 445]], dtype=int64) - outputs the same
Is there any possible way to speed up this search or is my solution the most efficient?有什么可能的方法可以加快搜索速度,或者我的解决方案是最有效的吗?
Thanks for any advices and suggestion!感谢您的任何意见和建议!
You can try this, the filter directly included in the numpy array!你可以试试这个,过滤器直接包含在 numpy 数组中!
import numpy as np
arr = np.array([998, 999, 1000, 1001])
filter_arr = arr > 999
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
https://www.w3schools.com/python/numpy_array_filter.asp https://www.w3schools.com/python/numpy_array_filter.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.