【发布时间】:2013-11-07 07:48:12
【问题描述】:
我有两个未知维度的数组A 和B,我想沿着Nth 维度连接它们。例如:
>>> A = rand(2,2) # just for illustration, dimensions should be unknown
>>> B = rand(2,2) # idem
>>> N = 5
>>> C = concatenate((A, B), axis=N)
numpy.core._internal.AxisError: axis 5 is out of bounds for array of dimension 2
>>> C = stack((A, B), axis=N)
numpy.core._internal.AxisError: axis 5 is out of bounds for array of dimension 3
问了一个相关问题here。不幸的是,当尺寸未知时,提出的解决方案不起作用,我们可能必须添加几个新轴,直到获得最小尺寸N。
我所做的是用 1 将形状扩展到 Nth 维度,然后连接:
newshapeA = A.shape + (1,) * (N + 1 - A.ndim)
newshapeB = B.shape + (1,) * (N + 1 - B.ndim)
concatenate((A.reshape(newshapeA), B.reshape(newshapeB)), axis=N)
例如,使用此代码,我应该能够将 (2,2,1,3) 数组与沿轴 3 的 (2,2) 数组连接起来。
有没有更好的方法来实现这一点?
ps:按照第一个答案的建议更新。
【问题讨论】:
标签: python arrays numpy concatenation