[英]Combine 2D arrays with different shape into a 3D array numpy
我正在嘗試將具有不同大小的 2D arrays 組合到 3D 數組中,如下所示:
a1 = np.array([[0,0,0,0,0,0],[1,1,1,1,1,1]])
print(a1.shape) #(2,6)
a2 = np.array([[0,0,0,0],[1,1,1,1]])
print(a2.shape) #(2,4)
combined = np.stack((a1,a2)) #ValueError: all input arrays must have the same shape
我正在嘗試獲得以下信息:
>>> [[[0,0,0,0,0,0],[1,1,1,1,1,1]],[[0,0,0,0],[1,1,1,1]]]
有人可以幫助我嗎?
正如numpy 文檔所說,arrays 必須具有相同的形狀。 嘗試這個:-
a1 = np.array([[0,0,0,0,0,0],[1,1,1,1,1,1]])
print(a1.shape) #(2,6)
# notice extra 2's and 3's to make it of same shape as a1
a2 = np.array([[0,0,0,0,2,2],[1,1,1,1,3,3]])
print(a2.shape) #(2,4)
combined = np.stack((a1,a2))
要得到這個: -
[[[0,0,0,0,0,0],[1,1,1,1,1,1]],[[0,0,0,0],[1,1,1,1]]]
您可以嘗試 python 列表。 如果你想堅持 numpy arrays 嘗試用 0 或其他東西填充 a2 數組,否則 a1 和 a2 的形狀不匹配不會沿着第三維堆疊它們。
它應該制作哪個最終數組:- 2x4x2(根據 a2 形狀)或 2x6x2(根據 a1 形狀)? 因為兩者的形狀不同。
numpy 中不能有非矩形形狀 arrays。 現在您有一些選擇,具體取決於您要實現的目標:
使用列表:
combined = [a1.tolist(), a2.tolist()] #[[[[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1]]], [[[0, 0, 0, 0], [1, 1, 1, 1]]]]
使用 arrays 的列表:
combined = [a1, a2] #[array([[[0, 0, 0, 0, 0, 0],[1, 1, 1, 1, 1, 1]]]), array([[[0, 0, 0, 0],[1, 1, 1, 1]]])]
使用列表數組:
combined = np.array([a1.tolist(), a2.tolist()]) #[[[list([0, 0, 0, 0, 0, 0]) list([1, 1, 1, 1, 1, 1])]], [[list([0, 0, 0, 0]) list([1, 1, 1, 1])]]]
我建議使用列表,因為當元素是像列表這樣的對象時,使用 numpy 並沒有太多好處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.