【问题标题】:Concatenation of numpy arrays of unknown dimension along arbitrary axis沿任意轴连接未知维度的 numpy 数组
【发布时间】:2013-11-07 07:48:12
【问题描述】:

我有两个未知维度的数组AB,我想沿着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


    【解决方案1】:

    这应该可行:

    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)
    

    【讨论】:

    • 在这里我想我必须做一堆手动重塑逻辑才能实现atleast_nd 函数。这要好得多。谢谢!
    【解决方案2】:

    我不认为你的方法有什么问题,虽然你可以让你的代码更紧凑一点:

    newshapeA = A.shape + (1,) * (N + 1 - A.ndim)
    

    【讨论】:

    • 谢谢!那好多了。尽管如此,我一直在寻找的是一些避免显式构造新形状的解决方案。 vstackdstack 仅对 2d 和 3d 数组执行我想要的操作。
    【解决方案3】:

    另一种选择,使用numpy.expand_dims

    >>> import numpy as np
    >>> A = np.random.rand(2,2)
    >>> B = np.random.rand(2,2)
    >>> N=5
    
    
    >>> while A.ndim < N:
            A= np.expand_dims(A,x)
    >>> while B.ndim < N:
            B= np.expand_dims(B,x)
    >>> np.concatenate((A,B),axis=N-1)
    

    【讨论】:

    • expand_dims 的核心是重塑:a.reshape(shape[:axis] + (1,) + shape[axis:]
    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2015-12-15
    • 2017-01-02
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    相关资源
    最近更新 更多