簡體   English   中英

按條件索引大型二維 numpy 數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM