簡體   English   中英

將二維numpy數組的行保存在另一個數組中

[英]Save rows of a bidimensional numpy array in another array

我有一個二維np數組V(100000x50)。 我想創建一個新數組V_tgt,在其中僅保留V的某些行,因此維將為(ix50)。 這樣做可能很容易,但是我嘗試了不同的方法,它似乎只保存了50個元素中的第一個。 我的代碼如下:

V_tgt = np.array([])
for i in IX_items:
    if i in IX_tgt_items:
        V_tgt=np.append(V_tgt, V[i])

我也嘗試了插入和刪除之類的功能,但是沒有用,如何保存所有值並創建尺寸正確的數組? 任何幫助都非常感謝。

根據您的評論,我假設您具有某種類型的目標索引列表(在我的示例中為tgt_idx1tgt_idx2 ),這些列表告訴您要從V中獲取哪些元素。您可以執行以下操作:

import numpy as np

V = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
tgt_idx1 = np.array([1, 2, 3])
tgt_idx2 = np.array([1, 3])


mask = []
for i, elem in enumerate(V):
    inTargets = i in tgt_idx1 and i in tgt_idx2
    mask.append(inTargets)
print mask

V_tgt = V[mask]
print V_tgt

此打印

[False, True, False, True]
[[ 4  5  6]
 [10 11 12]]

讓我們首先簡化問題。 帶有初始arraya ):

a = np.array([45, 29, 76, 23, 76, 98, 21, 63])

index arrays

i1 = np.array([1, 3, 5, 7, 9])
i2 = np.array([0, 1, 2, 3, 4])

那么我們可以用一個簡單的list理解來獲取元素a是在indexesi1i2

np.array([e for i, e in enumerate(a) if i in i1 and i in i2])

這是非常可讀和輸出:

array([29, 23])

我敢肯定,您可以將其適應給定arraysvariables

np.append的性能可能會消除這一點,為什么不創建兩個索引然后是子集的新重疊:

#using @Joe Iddons data
a = np.array([45, 29, 76, 23, 76, 98, 21, 63])
i1 = np.array([1, 3, 5, 7, 9])
i2 = np.array([0, 1, 2, 3, 4])

然后找到i1和i2的交集:

indices = np.intersect1d(i1,i2)

和子集:

a[indices]
array([29, 23])

暫無
暫無

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

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