簡體   English   中英

基於子數組的子數組在 Numpy 數組中搜索子數組的索引

[英]Searching a Numpy Array for the index of a subarray based on a subarray of the subarray

我想獲取包含特定數組的二維數組的索引。 在這種情況下,我想知道array [[4, 5], 6]在數組數組中的位置,但僅基於最里面的數組[4, 5]以便我得到它的 position 即使它不是六個將是一個八。

到目前為止,這是我的代碼:

import numpy as np

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

print(np.where(array == [4, 5]))

但作為 output 我得到:

(array([], dtype=int32), array([], dtype=int32))

我想要的 output 如下:

(array([1], dtype=int32), array([0], dtype=int32))

問題是您正在使用 dtype object 您的第一個 numpy 列包含列表對象。

您可以創建vectorized function來單獨檢查每個 object。

f = np.vectorize(lambda x: x==[4,5])
idx = np.where(f(array))
idx
(array([1]), array([0]))

您還可以在展平數組后使用list comprehension推導,然后對照[4,5]檢查每個 object 。 然后你可以使用np.where或者只是簡單的 boolean 檢查來獲取該平面列表中的索引,你可以unravel_index來獲取 position in the 2D array (我使用np.where是因為你想使用它)

check = [i==[4,5] for i in array.ravel()]
np.unravel_index(*np.where(check), array.shape)
(array([1]), array([0]))

暫無
暫無

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

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