簡體   English   中英

如何從數組數組中創建一個numpy數組?

[英]How to make a numpy array from an array of arrays?

我在ipython3實驗,在那里我創建了一個數組數組:

In [105]: counts_array
Out[105]: 
array([array([ 17,  59, 320, ...,   1,   7,   0], dtype=uint32),
       array([ 30,  71, 390, ...,  12,  20,   6], dtype=uint32),
       array([  7, 145, 214, ...,   4,  12,   0], dtype=uint32),
       array([ 23, 346, 381, ...,  15,  19,   5], dtype=uint32),
       array([ 51,  78, 270, ...,   3,   0,   2], dtype=uint32),
       array([212, 149, 511, ...,  19,  31,   8], dtype=uint32)], dtype=object)

In [106]: counts_array.shape
Out[106]: (6,)

In [107]: counts_array[0].shape
Out[107]: (1590,)

我想從我創建的這個怪物中獲得一個普通的shape=(6, 1590), dtype=uint32數組。

我怎樣才能做到這一點?

你可以使用np.vstack -

np.vstack(counts_array)

使用np.concatenate另一種方法 -

np.concatenate(counts_array).reshape(len(counts_array),-1)

樣品運行 -

In [23]: a
Out[23]: 
array([array([68, 92, 84, 35, 14, 71, 55, 40, 21, 41]),
       array([30, 90, 52, 64, 86, 68, 61, 85, 26, 98]),
       array([98, 64, 23, 49, 13, 17, 52, 96, 97, 19]),
       array([54, 26, 25, 22, 95, 77, 20, 73, 22, 80]),
       array([15, 84, 91, 54, 25, 21, 37, 19, 25, 25]),
       array([87, 17, 49, 74, 11, 34, 27, 23, 22, 83])], dtype=object)

In [24]: np.vstack(a)
Out[24]: 
array([[68, 92, 84, 35, 14, 71, 55, 40, 21, 41],
       [30, 90, 52, 64, 86, 68, 61, 85, 26, 98],
       [98, 64, 23, 49, 13, 17, 52, 96, 97, 19],
       [54, 26, 25, 22, 95, 77, 20, 73, 22, 80],
       [15, 84, 91, 54, 25, 21, 37, 19, 25, 25],
       [87, 17, 49, 74, 11, 34, 27, 23, 22, 83]])

經過各種實驗,結果證明以下簡單語法正常:

numpy.array([sub_array for sub_array in counts_array])

我的第一個工作版本不必要復雜:

numpy.array([[*sub_array] for sub_array in counts_array], dtype=numpy.uint32)

你考慮過numpy.vstack()嗎? 我經常使用它進行這種操作。

暫無
暫無

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

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