numpy stack vstack hstack concatenate

基本都用作连接字符串,只是连接维度不同,而且hstack和vstack 相对于stack,不受两个字符串shape必须相同的限制。

import numpy as np
test_1 = np.array([[1, 2, 3], [4, 5, 6]])
test_2 = np.array([[11, 12, 13], [14, 15, 16]])
#按照维度,如果axis = 2, 就是dim = 2的情况分解矩阵并连接
#将按第0维的个数,分别将第2维相对应位置的数字合并成一个小数组。该数组长度为shape[0]
#同理,当axis=1,按第0维个数,将第1维相应的数组合并,合并后的数组也是shape[0]的长度,
#如[[ 1,  2,  3],
#        [11, 12, 13]],就是分别从shape[0]下的第1维的[1,2,3]和[11,12,13]合并得到,长度为shape[0]
print('axis=2',np.stack((test_1, test_2), axis=2))
print('axis=1',np.stack((test_1, test_2), axis=1))
print('axis=0',np.stack((test_1, test_2), axis=0))

print('concat axis=1',np.concatenate((test_1,test_2),1))
print('hstack',np.hstack((test_1,test_2)))

print('concat axis=0',np.concatenate((test_1,test_2),0))
print('vstack',np.vstack((test_1,test_2)))
#np.concatenate axis = 0 is vstack
#np.concatenate axis = 1 is hstack
('axis=2', array([[[ 1, 11],
        [ 2, 12],
        [ 3, 13]],

       [[ 4, 14],
        [ 5, 15],
        [ 6, 16]]]))
('axis=1', array([[[ 1,  2,  3],
        [11, 12, 13]],

       [[ 4,  5,  6],
        [14, 15, 16]]]))
('axis=0', array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[11, 12, 13],
        [14, 15, 16]]]))
('concat axis=1', array([[ 1,  2,  3, 11, 12, 13],
       [ 4,  5,  6, 14, 15, 16]]))
('hstack', array([[ 1,  2,  3, 11, 12, 13],
       [ 4,  5,  6, 14, 15, 16]]))
('concat axis=0', array([[ 1,  2,  3],
       [ 4,  5,  6],
       [11, 12, 13],
       [14, 15, 16]]))
('vstack', array([[ 1,  2,  3],
       [ 4,  5,  6],
       [11, 12, 13],
       [14, 15, 16]]))
# 类似于np.stack(*****, axis=2)
test_1 = np.array([[1, 2, 3], [4, 5, 6]])
t = np.arange(1, 3).reshape((-1, 1))
print(np.hstack((t, test_1 )))
print t
print np.stack((t,test_1), axis = 2)
[[1 1 2 3]
 [2 4 5 6]]
[[1]
 [2]]



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-5-8375b98d2dd9> in <module>()
      4 print(np.hstack((t, test_1 )))
      5 print t
----> 6 print np.stack((t,test_1), axis = 2)


/Users/eclipsycn/anaconda2/lib/python2.7/site-packages/numpy/core/shape_base.pyc in stack(arrays, axis)
    352     shapes = set(arr.shape for arr in arrays)
    353     if len(shapes) != 1:
--> 354         raise ValueError('all input arrays must have the same shape')
    355 
    356     result_ndim = arrays[0].ndim + 1


ValueError: all input arrays must have the same shape
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值