np.hstack与np.vstack

np.hstack(tup)

tup: The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.

tup: 二维数组需要第一个维度相同;但是一维数组可以是任意长度

这是一个连接函数,将多个数组沿着水平方向连接(即对第2个维度进行连接)

二维数组连接的代码如下:

>>> a = np.array([[1],[2], [3]])
>>> b = np.array([[1,11],[2,22], [3,33]])
>>> a.shape
(3, 1)
>>> b.shape
(3, 2)
>>> np.hstack((a,b))
array([[ 1,  1, 11],
       [ 2,  2, 22],
       [ 3,  3, 33]])

一维数组连接的代码如下:

>>> np.hstack(([1,2], [3,4,5,6,7,8]))
array([1, 2, 3, 4, 5, 6, 7, 8])

注意:

不能将二维数组和一维数组进行连接,必须保证他们具有的维度个数相同;

多个数组应用元组()表示;

示例如下:

>>> np.hstack(([1,2], [[3],[4]]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/zhujun/anaconda3/lib/python3.6/site-packages/numpy/core/shape_base.py", line 286, in hstack
    return _nx.concatenate(arrs, 0)
ValueError: all the input arrays must have same number of dimensions

np.vstack(tup) 

The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

tup: 二维数组需要第二个维度相同;但是一维数组必须长度相同

这是一个连接函数,将多个数组沿着垂直方向连接(即对第1个维度进行连接) 

二维数组连接如下:

>>> a = np.array([[1,2]])
>>> b = np.array([[11,22],[33,44]])
>>> a.shape
(1, 2)
>>> b.shape
(2, 2)
>>> np.vstack((a,b))
array([[ 1,  2],
       [11, 22],
       [33, 44]])

一维数组连接如下:

>>> np.vstack(([1,2], [3,4]))
array([[1, 2],
       [3, 4]])

猜你喜欢

转载自blog.csdn.net/Ahead_J/article/details/85054762
np