python - 沿任意轴连接未知维度的numpy数组

标签 python arrays numpy concatenation

我有两个未知维度的数组 AB,我想将它们连接到第 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/

相关文章:

python - tf.group 和 tensorflow 集合有什么不同?

Java数组列表覆盖添加的数据并仅放置最后添加的项目

javascript - 在 JS 中迭代我的数组,但出现 "Cannot read property ' length' of undefined"错误

javascript - 跳过数组中包含特定数字的数字

numpy - 创建元素在范围内的二维 numpy 数组的最快方法

python - Python 中的 Matlab 内联函数

python - 代码适用于 Python 2,但不适用于 Python3 TypeError : a bytes-like object is required, 而不是 'str'

python - numpy.fft2 结果是否生成遵循 numpy.fft 文档中所述的标准排序的结果?

python - 为什么tensordot/reshape与kron不一致?

python - Pyparsing - 从解析操作中解析子语法