簡體   English   中英

如何將2d numpy數組列表連接到3d numpy數組?

[英]How can I concatenate a list of 2d numpy arrays into a 3d numpy array?

我嘗試了很多,但是沒有任何concatenatevstack可以為我工作。

您是否嘗試過np.array

np.array([[1,2],[3,4]])

通過串聯2個1d數組(列表)組成2d數組

相似地

np.array([np.ones(3,3), np.zeros(3,3)]]

應該產生一個(2,3,3)數組。

np.stack函數使您可以更好地控制要添加的軸。 它通過將所有輸入數組的維數加1並進行連接來工作。

您可以自己擴展尺寸,例如

In [378]: A=np.ones((2,3),int)
In [379]: B=np.zeros((2,3),int)
In [380]: np.concatenate([A[None,:,:], B[None,:,:]], axis=0)
Out[380]: 
array([[[1, 1, 1],
        [1, 1, 1]],

       [[0, 0, 0],
        [0, 0, 0]]])
In [381]: _.shape
Out[381]: (2, 2, 3)

要理解的關鍵是:

  • 匹配輸入的尺寸-除了要連接的尺寸外,它們必須匹配所有尺寸

  • 根據需要擴展輸入的維度。 要連接2d數組以形成3d,必須先將2d擴展為3d。 Nonenp.newaxis技巧特別有價值。

  • 沿右軸連接。

stackhstackvstack等都有助於實現這一點,但是熟練的numpy用戶應該能夠直接使用concatenate 在互動環節中練習小樣本。

In [385]: np.array((A,B)).shape
Out[385]: (2, 2, 3)
In [386]: np.stack((A,B)).shape
Out[386]: (2, 2, 3)
In [387]: np.stack((A,B),axis=1).shape
Out[387]: (2, 2, 3)
In [388]: np.stack((A,B),axis=2).shape
Out[388]: (2, 3, 2)

如果數組的形狀不同,則np.array將創建一個對象np.array數組

In [389]: C=np.ones((3,3))
In [390]: np.array((A,C))
Out[390]: 
array([array([[1, 1, 1],
       [1, 1, 1]]),
       array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])], dtype=object)
In [391]: _.shape
Out[391]: (2,)

dstack (和stack )在使用不同大小的數組時會遇到問題:

In [392]: np.dstack((A,B,C))
....
ValueError: all the input array dimensions except for the concatenation axis must match exactly

您可以使用np.dstack,文檔可以在這里找到: https ://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.dstack.html

import numpy as np

l1 = []
# create list of arrays
for i in range(5):
    l1.append(np.random.random((5, 3)))

# convert list of arrays into 3-dimensional array
d = np.dstack(l1)

d.shape #(5,3,5)

暫無
暫無

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

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