Concat两个不同维度的数组numpy

toe95027  于 2023-05-17  发布在  其他
关注(0)|答案(5)|浏览(122)

我尝试连接两个numpy数组以添加一个额外的列:array_1(569, 30)array_2(569, )
combined = np.concatenate((array_1, array_2), axis=1)
我认为如果我设置axis=2,它将垂直连接,这将工作。末端应该是569 x 31阵列。
我得到的错误是ValueError: all the input arrays must have same number of dimensions
有人能帮忙吗
谢谢!

v7pvogib

v7pvogib1#

可以使用numpy.column_stack

np.column_stack((array_1, array_2))

它隐式地将一维数组转换为二维数组,因此相当于@umutto注解的np.concatenate((array_1, array_2[:,None]), axis=1)

a = np.arange(6).reshape(2,3)
b = np.arange(2)

a
#array([[0, 1, 2],
#       [3, 4, 5]])

b
#array([0, 1])

np.column_stack((a, b))
#array([[0, 1, 2, 0],
#       [3, 4, 5, 1]])
v7pvogib

v7pvogib2#

把它们竖起来

np.vstack((array1,array2))
w7t8yxp5

w7t8yxp53#

您可以使用reshape函数将一维数组转换为具有相同行数的二维数组,并使用numpy的append函数水平连接生成的数组。
注意:在numpy的append函数中,我们必须提到我们想要插入值的轴。如果axis=0,则垂直追加数组。如果axis=1,则水平追加数组。因此,我们可以使用轴=1,用于当前要求
例如

a = np.arange(6).reshape(2,3)
b = np.arange(2)

a
#array([[0, 1, 2],
#       [3, 4, 5]])

b
#array([0, 1])

#First step, convert this 1-D array to 2-D (Number of rows should be same as array 'a' i.e. 2)
c = b.reshape(2,1)

c
#array([[0],
        [1]])

#Step 2, Using numpy's append function we can concatenate both arrays with same number of rows horizontally

requirement = np.append((a, c, axis=1))

requirement
#array([[0, 1, 2, 0],
#       [3, 4, 5, 1]])
olqngx59

olqngx594#

我写了一个通用的堆栈函数。它有点复杂,但它的输入只是数组(元组)和一个轴,你希望沿着这个轴堆叠数组。例如:

A = np.random.random((569, 30))
B = np.random.random((569,))
C = stack((A, B), axis=1)  # C.shape == (569, 31)


def stack(arrays: tuple | list, axis: int | None = None, reduce: bool = False) -> np.ndarray:
    """
    concatenate arrays along the specific axis

    if reduce=True, the "arrays" tuple is processed in this way
    arrays = (A, B, C, D)
    stack((stack((stack((A, B), axis=axis), C), axis=axis), D), axis=axis)
    This is potentially slower but allows to concatenate e.g.
    A.shape = (2, 4, 4)
    B.shape = (3, 4)
    C.shape = (4,)
    res = stack((C, B, A), axis=0, reduce=True)
    res.shape = (3, 4, 4)
    res[0] == stack((C, B), axis=0)
    res[1:] == A
    """

    @reduce_like
    def _stack(arrays: tuple | list, axis: int | None = None) -> np.ndarray:
        ndim = np.array([np.ndim(array) for array in arrays])
        _check_dims(ndim, reduce)

        if np.all(ndim == 1):  # vector + vector + ...
            if axis is None:  # -> vector
                return np.concatenate(arrays, axis=axis)
            else:  # -> 2-D array
                return np.stack(arrays, axis=axis)

        elif np.var(ndim) != 0:  # N-D array + (N-1)-D array + ... -> N-D array
            max_dim = np.max(ndim)

            # longest array
            shape = list(np.shape(arrays[np.argmax(ndim)]))
            shape[axis] = -1

            arrays = [np.reshape(a, shape) if np.ndim(a) < max_dim else a for a in arrays]
            return np.concatenate(arrays, axis=axis)

        elif is_constant(ndim):  # N-D array + N-D array + -> N-D array or (N+1)-D array
            ndim = ndim[0]
            if axis < ndim:  # along existing dimensions
                return np.concatenate(arrays, axis=axis)
            else:  # along a new dimension
                return np.stack(arrays, axis=axis)

    def _check_dims(ndim: np.ndarray, reduce: bool = False) -> None:
        error_msg = "Maximum allowed difference in dimension of concatenated arrays is one."

        if np.max(ndim) - np.min(ndim) > 1:
            if reduce:
                raise ValueError(error_msg)
            else:
                raise ValueError(f'{error_msg}\nUse "reduce=True" to unlock more general (but slower) stacking.')

    # 0-D arrays to 1-D arrays (to e.g. add a number to a vector)
    arrays = tuple([np.reshape(array, (1,)) if np.ndim(array) == 0 else array for array in arrays])

    if reduce:
        return _stack(arrays, axis)
    else:
        return _stack.undecorated(arrays, axis)
        
        
def is_constant(array: np.ndarray, axis: int | bool = None, constant: float = None) -> bool | np.ndarray:
    if constant is None:  # return True if the array is constant along the axis
        return np.var(array, axis=axis) < _num_eps
    else:  # return True if the array is equal to "constant" along the axis
        return np.all(np.abs(array - constant) < _num_eps, axis=axis)
        
        
def reduce_like(func: Callable):
    @wraps(func)
    def _decorator(*args, **kw):
        args = list(args)
        arrays = args[0]
        result = arrays[0]

        for array in arrays[1:-1]:
            if args[1:]:
                new_args = [(result, array), *args[1:]]
            else:
                new_args = [(result, array)]
            result = func(*new_args, **kw)
        else:
            if args[1:]:
                new_args = [(result, arrays[-1]), *args[1:]]
            else:
                new_args = [(result, arrays[-1])]

            return func(*new_args, **kw)

    _decorator.undecorated = func

    return _decorator
vxqlmq5t

vxqlmq5t5#

您可以简单地使用numpyhstack函数。
例如

import numpy as np

combined = np.hstack((array1,array2))

相关问题