我有两个未知维度的数组A和B,我想沿着N第th维连接它们。例如:
>>> 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的最小维数。
我所做的就是用1来扩展这个形状,直到N第四维,然后连接:
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)数组沿轴3连接起来。
是否有更好的方法来实现这一点?
ps:按建议更新第一个答案。
发布于 2013-10-28 15:51:11
我不认为您的方法有什么问题,尽管您可以使代码更加紧凑:
newshapeA = A.shape + (1,) * (N + 1 - A.ndim)https://stackoverflow.com/questions/19636487
复制相似问题