np.vstack()和np.hstack()

本文链接:https://blog.csdn.net/m0_37393514/article/details/79538748
在这里我们介绍两个拼接数组的方法:

np.vstack():在竖直方向上堆叠

np.hstack():在水平方向上平铺

import numpy as np
arr1=np.array([1,2,3])
arr2=np.array([4,5,6])
print np.vstack((arr1,arr2))

print np.hstack((arr1,arr2))

a1=np.array([[1,2],[3,4],[5,6]])
a2=np.array([[7,8],[9,10],[11,12]])
print a1
print a2
print np.hstack((a1,a2))
结果如下:
[[1 2 3]
[4 5 6]]
[1 2 3 4 5 6]
[[1 2]
[3 4]
[5 6]]
[[ 7 8]
[ 9 10]
[11 12]]
[[ 1 2 7 8]
[ 3 4 9 10]
[ 5 6 11 12]]
这里还需要强调一点,在hstack应用的时候,我在做cs231n上的assignment1的时候,我总是在hstack这里出错!才发现我以前学的很肤浅啊!

(1)np.hstack()

函数原型:numpy.hstack(tup)

其中tup是arrays序列,tup : sequence of ndarrays

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

等价于:np.concatenate(tup, axis=1)

例子一:

import numpy as np
brr1=np.array([1,2,3,4,55,6,7,77,8,9,99])
brr1_folds=np.array_split(brr1,3)
print brr1_folds
print brr1_folds[0:2]+brr1_folds[1:3]
print np.hstack((brr1_folds[:2]+brr1_folds[1:3]))
print brr1_folds[0:2]
print brr1_folds[1:3]
#print np.hstack((brr1_folds[0:2],brr1_folds[1:3]))

最后一行如果不注释掉就会出错;

[array([1, 2, 3, 4]), array([55, 6, 7, 77]), array([ 8, 9, 99])]
[array([1, 2, 3, 4]), array([55, 6, 7, 77]), array([55, 6, 7, 77]), array([ 8, 9, 99])]
[ 1 2 3 4 55 6 7 77 55 6 7 77 8 9 99]
[array([1, 2, 3, 4]), array([55, 6, 7, 77])]
[array([55, 6, 7, 77]), array([ 8, 9, 99])]
错误的原因就是以为我的array的维度不一致。改成+就好啦,加号是list的拼接!


例子二:

print np.hstack(([1,2,3,3,4],[3,4,5,8,6,6,7]))
结果是:表明了一维的数组hstack是随意的。

[1 2 3 3 4 3 4 5 8 6 6 7]

 

例子三:

表明我们的hstack必须要第二维度是一样的:

print np.hstack(([1,2,3,3,4],[3,4,5,8,6,6,7]))
print np.hstack(([[1,2,3],[2,3,4]],[[1,2],[2,3]]))
结果:

[1 2 3 3 4 3 4 5 8 6 6 7]
[[1 2 3 1 2]

 [2 3 4 2 3]]

如果你把上面改成下面就会报错了!!!

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

(2)np.vstack()

函数原型:numpy.hstack(tup)

tup : sequence of ndarrays

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

表示我们除了第一维可以不一样外,其他的维度上必须相同的shape。一维的数组必须大小一样。

例子一:

print np.vstack(([1,2,3],[3,4,3]))
print np.vstack(([1,2,3],[2,3]))
但是你要注意的是第二行是出错的!

例子二:

print np.vstack(([[1,2,3],[3,4,3]],[[1,3,4],[2,4,5]]))
print np.vstack(([[1,2,3],[3,4,3]],[[3,4],[4,5]]))
同样的表明了,如果我们的数组的第二维不一样所以出错了。

print np.vstack(([[1,2,3],[3,4,3]],[[2,4,5]]))
print np.vstack(([[1,2,3],[3,4,3]],[[4,5]]))
例子三:

我们传入的是list:

import numpy as np
arr1=np.array([[1,2],[2,4],[11,33],[2,44],[55,77],[11,22],[55,67],[67,89]])
arr11=np.array([[11,2,3],[22,3,4],[4,5,6]])
arr1_folds=np.array_split(arr1,3)
print arr1_folds
print np.vstack(arr1_folds)


结果:

[array([[ 1, 2],
[ 2, 4],
[11, 33]]), array([[ 2, 44],
[55, 77],
[11, 22]]), array([[55, 67],
[67, 89]])]
[[ 1 2]
[ 2 4]
[11 33]
[ 2 44]
[55 77]
[11 22]
[55 67]
[67 89]]

 

posted @ 2019-11-18 15:00  瘋耔  阅读(750)  评论(0编辑  收藏  举报
跳至侧栏