按条件索引大型2d numpy数组

2024-03-28 15:07:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个2D numpython数组,即(15003712)。我想找出数组中值在-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

因为它是一个非常大的数组,有什么方法可以让它更快?你知道吗


Tags: andinforindexifvaluenp数组
3条回答

假设您的lon\u数组是numpy数组,您可以使用以下方法:

find_index = np.where(np.logical_and(lon_array >= -40, lon_arr <= -10))
index =  np.asarray(find_index).T

自np.哪里只需要一个条件,就可以将两个条件结合起来得到中间条件np.u和. 你知道吗

也可以作为一个内衬:

>>> 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))

相关问题 更多 >