Python数据分析学习笔记二

来源:互联网 发布:web数据挖掘的特点 编辑:程序博客网 时间:2024/04/26 09:17

一、NumPy初识(2)


4、数组的组合

NumPy中的数组组合有水平组合、垂直组合、深度组合和列组合等多种组合方式。

水平组合:

使用hstack()函数可以完成数组的水平拼接,例:

import numpy as npa1 = np.arange(9).reshape(3,3)print a1a2 = a1 * 2print a2b = np.hstack((a1,a2))print b

输出结果:

[[0 1 2] [3 4 5] [6 7 8]][[ 0  2  4] [ 6  8 10] [12 14 16]][[ 0  1  2  0  2  4] [ 3  4  5  6  8 10] [ 6  7  8 12 14 16]]

由上面的代码可以得到,所谓水平组合,就是将数组a1,a2的每一行进行拼接得到一行,数组的行数不变,列数增加
上面的效果也可以使用concatenate函数实现

import numpy as npa1 = np.arange(9).reshape(3,3)print a1a2 = a1 * 2print a2b = np.concatenate((a1,a2),axis=1)print b

输出效果与上一个程序一样,需要注意的是,在这两个函数内需要传入的都是Python的元组,所以应该在a1,a2外加上括号();

垂直组合:

由上面的程序效果可以推导出,所谓的垂直组合就是将两个数组的每一列进行拼接,数组的列数不变,行数增加,例如:

import numpy as npa1 = np.arange(9).reshape(3,3)print a1a2 = a1 * 2print a2b = np.vstack((a1,a2))print b

输出结果:

[[0 1 2] [3 4 5] [6 7 8]][[ 0  2  4] [ 6  8 10] [12 14 16]][[ 0  1  2] [ 3  4  5] [ 6  7  8] [ 0  2  4] [ 6  8 10] [12 14 16]]

同样,在这里我们也可以使用concatenate函数进行实现,只需要将axis的参数设置为0就可以了,例:

import numpy as npa1 = np.arange(9).reshape(3,3)print a1a2 = a1 * 2print a2b = np.concatenate((a1,a2),axis=0)print b

深度组合:

import numpy as npa1 = np.arange(9).reshape(3,3)print a1a2 = a1 * 2print a2b = np.dstack((a1,a2))print b.shapeprint b

输出结果:

[[0 1 2] [3 4 5] [6 7 8]][[ 0  2  4] [ 6  8 10] [12 14 16]](3, 3, 2)[    [        [ 0  0]        [ 1  2]        [ 2  4]    ]    [        [ 3  6]        [ 4  8]        [ 5 10]    ]    [        [ 6 12]        [ 7 14]        [ 8 16]    ]]

可以看出,深度组合不仅进行了数组的组合,还改变了数组的维度,也就是将一系列数组沿着纵轴(深度)方向进行层叠组合。也就是组合成为一个z轴为2,x轴3,y轴为3的三维数组。

列组合

import numpy as npa1 = np.arange(9).reshape(3,3)print a1a2 = a1 * 2print a2b = np.column_stack((a1,a2))print b.shapeprint b

输出结果:

[[0 1 2] [3 4 5] [6 7 8]][[ 0  2  4] [ 6  8 10] [12 14 16]](3, 6)[[ 0  1  2  0  2  4] [ 3  4  5  6  8 10] [ 6  7  8 12 14 16]]

显示结果可以看到,实际上对于二维数组而言,hstack 和column_stack的效果是一样的。
但是对于一位数组来说,则会将两个数组覆盖成为一个二维数组,将每一个数组的每一列一一对应组成二维数组的一列,例:

import numpy as npa1 = np.arange(10)a2 = np.arange(1,11)b = np.column_stack((a1,a2))print b.shapeprint b

输出结果:

(10, 2)[[ 0  1] [ 1  2] [ 2  3] [ 3  4] [ 4  5] [ 5  6] [ 6  7] [ 7  8] [ 8  9] [ 9 10]]

行组合:
行组合的特性与列组合是一致的,可以通过下面的例子比较一下:

一维数组:

import numpy as npa1 = np.arange(10)a2 = np.arange(1,11)b = np.row_stack((a1,a2))print b.shapeprint b

输出结果:

(2, 10)[[ 0  1  2  3  4  5  6  7  8  9] [ 1  2  3  4  5  6  7  8  9 10]]

二维数组:

import numpy as npa1 = np.arange(9).reshape(3,3)print a1a2 = a1 * 2print a2b = np.row_stack((a1,a2))print b.shapeprint b

输出结果:

[[0 1 2] [3 4 5] [6 7 8]][[ 0  2  4] [ 6  8 10] [12 14 16]](6, 3)[[ 0  1  2] [ 3  4  5] [ 6  7  8] [ 0  2  4] [ 6  8 10] [12 14 16]]
0 0