簡體   English   中英

在多個維度中擴展一維 numpy 數組

[英]Extend 1d numpy array in multiple dimensions

我有一個 1d numpy 數組,例如 a=[10,12,15] 並且我想擴展它,以便我最終得到一個形狀為 (3,10,15,20) 的 numpy 數組 b,其中填充了 a 以便例如 b[:,1,1,1] 是 [10,12,15]。 我想過使用 np.repeat 但我不清楚該怎么做?

tile會為你做的。 在內部,這會為每個軸repeat一次。

In [114]: a = np.array([10,12,15])
In [115]: A = np.tile(a.reshape(3,1,1,1),(1,10,15,20))
In [116]: A.shape
Out[116]: (3, 10, 15, 20)
In [117]: A[:,1,1,1]
Out[117]: array([10, 12, 15])

對於某些目的,僅進行reshape並讓broadcasting根據需要擴展維度可能就足夠了(而不實際擴展內存使用)。

代碼:

import numpy as np

a = np.arange(1800).reshape((10,12,15))
b = np.repeat(a, repeats=5, axis=0).reshape(((3,10,15,20)))

如果您想以不同的方式重復,您可以更改軸。 要理解重復使用較低的形狀,例如 a(3,5,4) 和 b (2,3,5,4) 並在不同的軸上重復。

暫無
暫無

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

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