我有两个未知维度的数组A
和B
,我想沿着第N
个维度将它们连接起来。例如:
>>> 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
这里有一个相关的问题被问到这里。不幸的是,提出的解决方案在维度未知时不起作用,我们可能需要添加多个新轴直到获得最小维度N
。
我的做法是将形状扩展到第N
维,并添加 1 直到要连接的数组具有相同的形状:
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)的数组与一个形状为(2,2)的数组沿着axis 3连接起来。
有更好的方法实现这个功能吗?
ps: 根据第一个回答的建议进行了更新。
atleast_nd
函数,但这样太好了。谢谢! - tel