[英]Appending multi-dimensional arrays of different shapes in Python
數組C1
和C2
分別具有形狀(1, 2, 2)
和(1, 1, 2)
。 我想將這些數組附加到一個新數組C3
中。 但我收到一個錯誤。 附加了所需的輸出。
import numpy as np
arC1 = []
arC2 = []
C1=np.array([[[0, 1],[0,2]]])
arC1.append(C1)
C2=np.array([[[1,1]]])
C2.shape
arC2.append(C2)
C3=np.append(C1,C2,axis=0)
錯誤是
<module>
C3=np.append(C1,C2,axis=0)
File "<__array_function__ internals>", line 5, in append
File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\function_base.py", line 4745, in append
return concatenate((arr, values), axis=axis)
File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 2 and the array at index 1 has size 1
所需的輸出是
C3[0]=np.array([[[0, 1], [0, 2]]])
C3[1]=np.array([[2,3]])
C1 = np.array([[[0, 1],[0,2]]])
print(C1.shape) # (1, 2, 2)
C2 = np.array([[[1,1]]])
print(C2.shape) # (1, 1, 2)
如果你跑
C3 = np.append(C1,C2,axis=1)
print(C2.shape) # (1, 3, 2)
意思是這樣的。 (1, 2 , 2) + (1, 1 , 2) = (1, 3 , 2)
如果你跑
C3 = np.append(C1,C2,axis=0)
意思是這樣的。 ( 1 , 2, 2) + ( 1 , 1, 2) = ( 2 , ?? , 2)
由於numpy是一個矩陣,所以不能相加,因為低維不同。
簡單來說,當你在append函數中設置axis參數值來追加兩個數組時,除了軸對應的維度的值之外,所有維度的值都應該相同
C1 = np.array([[[[[0, 1]]],[[[0, 2]]], [[[0, 2]]]]])
C2 = np.array([[[[[1]]],[[[2]]], [[[3]]]]])
C3 = np.append(C1, C2, axis=4)
如果尺寸如下,
(1, 3, 1, 1, 2) # C1
(1, 3, 1, 1, 1) # C2
-->
(1, 3, 1, 1, 3) # C3
只有軸 4 尺寸不同,所以你可以做np.append(C1, C2, axis=4)
C1 = np.array([[[[[0, 1]]],[[[0, 2]]], [[[0, 2]]]]])
C2 = np.array([[[[[1, 1]]],[[[2, 2]]], [[[3, 3]]]], [[[[1, 1]]],[[[2, 2]]], [[[3, 3]]]]])
C3 = np.append(C1, C2, axis=0)
如果尺寸如下,
(1, 3, 1, 1, 2) # C1
(2, 3, 1, 1, 2) # C2
-->
(3, 3, 1, 1, 2) # C3
只有軸 0 尺寸不同,所以你可以做np.append(C1, C2, axis=0)
C1 = np.array([[[[[0, 1]]],[[[0, 2]]], [[[0, 2]]]]])
C2 = np.array([[[[[1]]],[[[2]]], [[[3]]]], [[[[1]]],[[[2]]], [[[3]]]]])
如果尺寸如下,
(1, 3, 1, 1, 2) # C1
(2, 3, 1, 1, 1) # C2
-->
ERROR
除了您指定的 Axis 值之外,至少有一個維度更加不同。 所以不可能用這些數組設置軸參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.