我有两个未知维度的数组 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
问了一个相关问题here .不幸的是,当尺寸未知时,所提出的解决方案不起作用,我们可能必须添加几个新轴,直到获得 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)
例如,通过这段代码,我应该能够沿轴 3 连接一个 (2,2,1,3) 数组和一个 (2,2) 数组。
是否有更好的方法来实现这一目标?
ps:根据第一个答案的建议进行了更新。
最佳答案
这应该有效:
def atleast_nd(x, n):
return np.array(x, ndmin=n, subok=True, copy=False)
np.concatenate((atleast_nd(a, N+1), atleast_nd(b, N+1)), axis=N)
关于python - 沿任意轴连接未知维度的numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19636487/