# Numpy中数组拼接

## Numpy中不同数组拼接

Posted by Jae on February 21, 2019

#### 多个不同的数组沿着不同的轴拼接在一起

import numpy as np
a = np.arange(4).reshape((2, 2))

a
array([[0, 1],
[2, 3]])

b = np.array([[4, 5],[6, 7]])

b
array([[4, 5],
[6, 7]])

a和b都是2x2的矩阵

np.vstack((a, b))
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])

np.hstack((a, b))
array([[0, 1, 4, 5],
[2, 3, 6, 7]])

v = np.array([8, 9])

np.vstack((a, v))
array([[0, 1],
[2, 3],
[8, 9]])

np.hstack((a, v))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-712051f7bc6a> in <module>()
----> 1 np.hstack((a, v))

~/anaconda3/lib/python3.6/site-packages/numpy/core/shape_base.py in hstack(tup)
286         return _nx.concatenate(arrs, 0)
287     else:
--> 288         return _nx.concatenate(arrs, 1)
289
290
ValueError: all the input arrays must have same number of dimensions


#### 合并一维数组到2维数组

采用np.column_stack函数将1维数组合并到二维数组上
np.column_stack((a, v))
array([[0, 1, 8],
[2, 3, 9]])


< script src = " / js / bootstrap.min.js " >