numpy数组的拆分和组合
#数组的拆分和组合
def testth10():a = np.arange(1,7).reshape(2,3)b = np.arange(21,27).reshape(2,3)#垂直方向c = np.vstack((a,b)) #将a和b组合到一起print(c)d = np.vsplit(c,2) #把数组c拆成2个数组print(d)#水平方向e = np.hstack((a, b)) # 将a和b组合到一起print(e)f = np.hsplit(e, 2) # 把数组c拆成2个数组print(f)
测试结果:
垂直:
[[ 1 2 3]
[ 4 5 6]
[21 22 23]
[24 25 26]]
[array([[1, 2, 3],
[4, 5, 6]]), array([[21, 22, 23],
[24, 25, 26]])]水平:
[[ 1 2 3 21 22 23]
[ 4 5 6 24 25 26]]
[array([[1, 2, 3],
[4, 5, 6]]), array([[21, 22, 23],
[24, 25, 26]])]
长度不等的数组组合
# 长度不等的数组组合
def testht11():a = np.array([1,2,3,4,5])b = np.array([1,2,3,4])#填充b数组使其长度与a相同#前补0个元素,后补1个元素,都补不上-1b = np.pad(b,pad_width=(0,1),mode = 'constant',constant_values=-1)print(b)#垂直方向完成组合操作,生成新数组c = np.vstack((a,b))print(c)
测试结果:
[ 1 2 3 4 -1]
[[ 1 2 3 4 5]
[ 1 2 3 4 -1]]
#多维数组的组合和拆分
def testht12():#通过axis作为关键字参数指定组合的方向,取值如下:#若待组合的数组都是二位数组:# 0:垂直方向组合# 1:水平方向组合# 若待组合的数组都是三维数组:# 0:垂直方向组合# 1:水平方向组合# 2:深度方向组合# np.concatenate((a,b),axis=0)# #通过给出的数组与要拆分的分数,按照某个方向进行拆分,axis的取值同上# np.split(c,2,axis=0)a = np.arange(1, 7).reshape(2, 3)b = np.arange(21, 27).reshape(2, 3)c = np.concatenate((a,b),axis=1)#水平方向print(c)c = np.split(c,2,axis=1)#c数组水平方向拆成2个数组print(c)
测试结果:
[[ 1 2 3 21 22 23]
[ 4 5 6 24 25 26]]
[array([[1, 2, 3],
[4, 5, 6]]), array([[21, 22, 23],
[24, 25, 26]])]
def testht13():a = np.arange(1,9)b = np.arange(9,17)#吧俩个数组组合在一起成俩行c = np.row_stack((a,b))print(c)#把俩个数组组合在一起成俩列d = np.column_stack((a,b))print(d)
测试结果:
[[ 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16]]
[[ 1 9]
[ 2 10]
[ 3 11]
[ 4 12]
[ 5 13]
[ 6 14]
[ 7 15]
[ 8 16]]