[英]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.