[英]Indexing large 2d numpy array by conditions
我有一个形状为 (1500, 3712) 的 2D NumPy 数组。 我想找到值在 -10 到 -40 之间的数组索引。 到目前为止,我有:
for item in lon_array:
for value in item:
if value >= -40 and value <= -10:
find_index = np.where(lon_array == value)
index = np.asarray(find_index).T
既然它是一个非常大的数组,有没有办法让它更快?
假设您的lon_array
是一个 NumPy 数组,您可以使用以下方法:
find_index = np.where(np.logical_and(lon_array >= -40, lon_arr <= -10))
index = np.asarray(find_index).T
由于np.where
只需要一个条件,您可以将两个条件结合起来使用np.logical_and
来获得 between 条件。
它也可以作为单线完成:
>>> lon_arr
array([[ 20, -40],
[ 30, -30],
[ 20, -14],
[ 30, -30]])
>>> np.asarray(np.where(np.logical_and(lon_arr>=-40, lon_arr<=-10))).T
array([[0, 1],
[1, 1],
[2, 1],
[3, 1]])
如果lon_array
是列表列表(Python 的内置基本数据类型),则使用enumerate(...)
将是了解元素索引的最佳方法:
for y, row in enumerate(lon_array):
for x, value in enumerate(row):
if -40 <= value <= -10:
index = (y, x)
# do something useful with it...
使用numpy.where
,您可以根据数据的值提取索引,并保持在构建numpy
的优化c code
执行的数据的迭代:
import numpy as np
x = np.random.random(10).reshape(2, 5)
print(x)
indices = np.where(x < 0.2) #<--- this selects the indices based on a filter
print(indices)
x[indices]
[[ 0.11129659 0.33608351 0.07542966 0.44118394 0.14848829]
[ 0.8475123 0.27994122 0.91797756 0.02662857 0.52820238]]
# These are the indices produced by np.where:
# the first array contains the rows `i` and the second the columns `j`
(array([0, 0, 0, 1]), array([0, 2, 4, 3]))
array([ 0.11129659, 0.07542966, 0.14848829, 0.02662857])
因为您的过滤器中有两个条件,我建议您使用以下构造来构建比np.where
直接接受的更复杂的布尔表达式:
indices = np.where(np.logical_or(x < 0.2, x > 0.8))
为了完整numpy.indices
,您可以使用numpy.indices
作为其他答案中提出的基于numpy.where
的解决方案的替代方案:
In [1245]: lon_array = np.linspace(-70, 20, 10).reshape(2, 5)
In [1246]: lon_array
Out[1246]:
array([[-70., -60., -50., -40., -30.],
[-20., -10., 0., 10., 20.]])
In [1247]: idx = np.nonzero(np.logical_and(lon_array >= -40, lon_array <= -10))
In [1248]: idx
Out[1248]: (array([0, 0, 1, 1], dtype=int64), array([3, 4, 0, 1], dtype=int64))
In [1249]: lon_array[idx]
Out[1249]: array([-40., -30., -20., -10.])
上面的演示显示 NumPy 的nonzero
返回一个一维数组元组,当用作选择对象时会触发高级索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.