繁体   English   中英

在 Python 中附加不同形状的多维数组

[英]Appending multi-dimensional arrays of different shapes in Python

数组C1C2分别具有形状(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参数值来追加两个数组时,除了轴对应的维度的值之外,所有维度的值都应该相同

示例 1

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)

示例 2

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)

示例 3

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM