簡體   English   中英

如何從一維數組中獲取二維索引數組?

[英]How to get 2d array of indices from 1d array?

我正在尋找一種有效的方法來根據一維數組中的值返回二維數組的索引。 我目前有一個嵌套的 for 循環設置,它非常緩慢。

這是一些示例數據以及我想獲得的內容:

data2d = np.array( [  [1,2] , [1,3] ,[3,4], [1,2] , [7,9] ])

data1d = np.array([1,2,3,4,5,6,7,8,9])

我想返回 data2d 等於 data1d 的索引。 我想要的輸出是這個二維數組:

locs = np.array([[0, 1], [0, 2], [2, 3], [0, 1], [6, 8]])

我唯一想到的是嵌套的 for 循環:

locs = np.full((np.shape(data2d)), np.nan)

for i in range(0, 5):
    for j in range(0, 2):
        loc_val = np.where(data1d == data2d[i, j])
        loc_val = loc_val[0]
        locs[i, j] = loc_val

這對於一小組數據來說沒問題,但我有 87,600 個 2d 網格,每個網格點為 428x614。

使用np.searchsorted

np.searchsorted(data1d, data2d.ravel()).reshape(data2d.shape)

array([[0, 1],
       [0, 2],
       [2, 3],
       [0, 1],
       [6, 8]])

searchsorted執行二進制與弄明白搜索data2d 然后重新塑造結果。


另一種選擇是建立一個索引並在恆定時間內查詢它。 您可以使用 Pandas 的Index API 來做到這一點。

import pandas as pd

idx = pd.Index([1,2,3,4,5,6,7,8,9])
idx
#  Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

idx.get_indexer(data2d.ravel()).reshape(data2d.shape)

array([[0, 1],
       [0, 2],
       [2, 3],
       [0, 1],
       [6, 8]])

這也應該很快

import numpy as np
data2d = np.array( [  [1,2] , [1,3] ,[3,4], [1,2] , [7,9] ])
data1d = np.array([1,2,3,4,5,6,7,8,9])
idxdict = dict(zip(data1d,range(len(data1d))))
locs = data2d
for i in range(len(locs)):
    for j in range(len(locs[i])):
        locs[i][j] = idxdict[locs[i][j]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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