簡體   English   中英

Numpy 堆棧在第一維?

[英]Numpy stack in the first dimension?

我有兩個形狀為 (3,8) 的 np.arrays,我怎樣才能將其變成 (2,3,8) 我嘗試使用 np.concatenate 但它只給了我

回溯(最近一次調用最后):文件“”,第 1 行,在文件“< array_function internals>”中,第 6 行,在連接類型錯誤:只有 integer 標量 arrays 可以轉換為標量索引

錯誤。 我的 a1 數組:

數組([[0.08, 0.3, 0.51, 0.37, 0.02, 0.52, 0.05, 0.08], [0.77, 0.01, 0.08, 0.67, 0.01, 0.02, 0.17, 0.77], [0.3, 0. , 0.07, 0.17, 0.11 , 0.04, 0.05, 0.34]], dtype=float32)

我的 a2 數組:

數組([[0.08, 0.3, 0.51, 0.37, 0.02, 0.52, 0.05, 0.08], [0.77, 0.01, 0.08, 0.67, 0.01, 0.02, 0.17, 0.77], [0.3, 0. , 0.07, 0.17, 0.11 , 0.04, 0.05, 0.34]], dtype=float32)

嘗試做:

a1 = a1.reshape((1,3,8))
a2 = a2.reshape((1,3,8))
np.concatenate((a1,a2))

或者

array = np.concatenate((a1.reshape((1,3,8)),a2.reshape((1,3,8))))

根據錯誤消息,您似乎也忘記在np.concatenate()中的 arrays 周圍包含括號。

嘗試以下簡單的方法來堆疊您的數組:

>>> import numpy as np
>>> a = np.array([[0.08, 0.3 , 0.51, 0.37, 0.02, 0.52, 0.05, 0.08], [0.77, 0.01, 0.08, 0.67, 0.01, 0.02, 0.17, 0.77], [0.3 , 0. , 0.07, 0.17, 0.11, 0.04, 0.05, 0.34]])
>>> a.shape
(3, 8)
>>> b = np.array([[0.08, 0.3 , 0.51, 0.37, 0.02, 0.52, 0.05, 0.08], [0.77, 0.01, 0.08, 0.67, 0.01, 0.02, 0.17, 0.77], [0.3 , 0. , 0.07, 0.17, 0.11, 0.04, 0.05, 0.34]])
>>> b.shape
(3, 8)
>>> c = np.array([a, b])
>>> c.shape
(2, 3, 8)
>>> 

雖然np.concatenate需要在@Tim Crammond 的答案中創建的現有尺寸,但np.stack將為您創建軸:

np.stack((a, b), axis=0)

這大致相當於@Sophie np.array直接使用np.array 的建議

暫無
暫無

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

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