追加不同维度的数组以获得单个数组

时间:2017-11-27 17:07:04

标签: python arrays numpy append

我有三个向量(numpy数组),vector_1, vector_2, vector_3  如下:

尺寸(向量1)=(200,2048)

尺寸(vector2)=(200,8192)

尺寸(的Vector3)=(200,32768)

我想将这些向量附加到 vector_4

尺寸(vector4)=(200,2048 + 8192 + 32768)=(200,43008)

分别添加vector1,然后添加vector2,然后添加vector3

尝试以下方法:

vector4=numpy.concatenate((vector1,vector2,vector3),axis=0)

ValueError: all the input array dimensions except for the concatenation axis must match exactly

vector4=numpy.append(vector4,[vector1,vector2,vectors3],axis=0)

TypeError: append() missing 1 required positional argument: 'values'

2 个答案:

答案 0 :(得分:1)

我相信您正在寻找numpy.hstack

>>> import numpy as np
>>> a = np.arange(4).reshape(2,2)
>>> b = np.arange(6).reshape(2,3)
>>> c = np.arange(8).reshape(2,4)
>>> a
array([[0, 1],
       [2, 3]])
>>> b
array([[0, 1, 2],
       [3, 4, 5]])
>>> c
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>> np.hstack((a,b,c))
array([[0, 1, 0, 1, 2, 0, 1, 2, 3],
       [2, 3, 3, 4, 5, 4, 5, 6, 7]])

答案 1 :(得分:0)

错误消息几乎告诉您究竟是什么问题:

ValueError: all the input array dimensions except for the concatenation axis must match exactly

但是你正在做相反的事情,连接轴尺寸完全匹配,但其他尺寸不匹配。考虑:

In [3]: arr1 = np.random.randint(0,10,(20, 5))

In [4]: arr2 = np.random.randint(0,10,(20, 3))

In [5]: arr3 = np.random.randint(0,10,(20, 11))

注意尺寸。只要给它正确的轴。所以使用第二个而不是第一个:

In [8]: arr1.shape, arr2.shape, arr3.shape
Out[8]: ((20, 5), (20, 3), (20, 11))

In [9]: np.concatenate((arr1, arr2, arr3), axis=1)
Out[9]:
array([[3, 1, 4, 7, 3, 6, 1, 1, 6, 7, 4, 6, 8, 6, 2, 8, 2, 5, 0],
       [4, 2, 2, 1, 7, 8, 0, 7, 2, 2, 3, 9, 8, 0, 7, 3, 5, 9, 6],
       [2, 8, 9, 8, 5, 3, 5, 8, 5, 2, 4, 1, 2, 0, 3, 2, 9, 1, 0],
       [6, 7, 3, 5, 6, 8, 3, 8, 4, 8, 1, 5, 4, 4, 6, 4, 0, 3, 4],
       [3, 5, 8, 8, 7, 7, 4, 8, 7, 3, 8, 7, 0, 2, 8, 9, 1, 9, 0],
       [5, 4, 8, 3, 7, 8, 3, 2, 7, 8, 2, 4, 8, 0, 6, 9, 2, 0, 3],
       [0, 0, 1, 8, 6, 4, 4, 4, 2, 8, 4, 1, 4, 1, 3, 1, 5, 5, 1],
       [1, 6, 3, 3, 9, 2, 3, 4, 9, 2, 6, 1, 4, 1, 5, 6, 0, 1, 9],
       [4, 5, 4, 7, 1, 4, 0, 8, 8, 1, 6, 0, 4, 6, 3, 1, 2, 5, 2],
       [6, 4, 3, 2, 9, 4, 1, 7, 7, 0, 0, 5, 9, 3, 7, 4, 5, 6, 1],
       [7, 7, 0, 4, 1, 9, 9, 1, 0, 1, 8, 3, 6, 0, 5, 1, 4, 0, 7],
       [7, 9, 0, 4, 0, 5, 5, 9, 8, 9, 9, 7, 8, 8, 2, 6, 2, 3, 1],
       [4, 1, 6, 5, 4, 5, 6, 7, 9, 2, 5, 8, 6, 6, 6, 8, 2, 3, 1],
       [7, 7, 8, 5, 0, 8, 5, 6, 4, 4, 3, 5, 9, 8, 7, 9, 8, 8, 1],
       [3, 9, 3, 6, 3, 2, 2, 4, 0, 1, 0, 4, 3, 0, 1, 3, 4, 1, 3],
       [5, 1, 9, 7, 1, 8, 3, 9, 4, 7, 6, 7, 4, 7, 0, 1, 2, 8, 7],
       [6, 3, 8, 0, 6, 2, 1, 8, 1, 0, 0, 3, 7, 2, 1, 5, 7, 0, 7],
       [5, 4, 7, 5, 5, 8, 3, 2, 6, 1, 0, 4, 6, 9, 7, 3, 9, 2, 5],
       [1, 4, 8, 5, 7, 2, 0, 2, 6, 2, 6, 5, 5, 4, 6, 1, 8, 8, 1],
       [4, 4, 5, 6, 2, 6, 0, 5, 1, 8, 4, 5, 8, 9, 2, 1, 0, 4, 2]])

In [10]: np.concatenate((arr1, arr2, arr3), axis=1).shape
Out[10]: (20, 19)