上一个博客写到了numpy的特性,如何安装以及功能初探。这一篇就讲讲numpy的常用功能以及与其它python库的结合使用。
假设你已经成功执行下列语句:
import numpy as np
初始化
(1)直接创建
## 创建一维数组
In [8]: test_list = [1,3,5,6,7]
In [9]: array_numpy = np.array(test_list)
In [10]: array_numpy
Out[10]: array([1, 3, 5, 6, 7])
## 创建多维数组
In [16]: test_n_list = [[1,2,3], [4,5,6]]
In [17]: array_n_numpy = np.array(test_n_list)
In [18]: array_n_numpy
Out[18]:
array([[1, 2, 3],
[4, 5, 6]])
In [19]:
(2)读图创建
假设现在目录下有个test.jpg图片,可以读图进行初始化
In [19]: from PIL import Image
In [20]: im = Image.open('test.jpg') # 读入图片
In [21]: im.show() # 显示图片
In [22]: print im.mode, im.size, im.format # 打印图片的相关信息
RGB (1920, 1200) JPEG # RGB图像
In [23]: im_numpy = np.asarray(im) # 把读入的图片作为矩阵
In [24]: im_numpy.shape # 图片矩阵的shape信息
Out[24]: (1200, 1920, 3) # 三维矩阵,每个分量是原始图片的R、G、B信息
(3)使用内置函数创建
In [25]: array_n_dim = np.ones((3,4,4), dtype='int8') # 创建全1的矩阵
In [26]: array_n_dim
Out[26]:
array([[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]], dtype=int8)
In [27]: array_n_dim.shape
Out[27]: (3, 4, 4) # 三维矩阵,每个维度大小是4*4的
相关信息
(1)数据类型(dtype)
可以在创建矩阵的时候指定数据类型,像上面的例子那样,也可以之后进行转换
In [28]: array_n_numpy
Out[28]:
array([[1, 2, 3],
[4, 5, 6]])
In [29]: array_n_numpy.dtype
Out[29]: dtype('int64') # 现在的数据类型是int64
In [30]: array_n_numpy.astype(np.float32) # 显式的转化为float32
Out[30]:
array([[ 1., 2., 3.],
[ 4., 5., 6.]], dtype=float32)
################# 如果每个字符串数组表示的全部是数字,可以这样将其转化为数字数组
In [31]: string_list = np.array(['1.2', '3', '4.67'], dtype= np.string_)
In [32]: string_list # 字符串数组
Out[32]:
array(['1.2', '3', '4.67'],
dtype='|S4')
In [33]: string_list.astype(float) # numpy自动转换为float合适的表示,对于此例是float64
Out[33]: array([ 1.2 , 3. , 4.67])
In [34]: string_list.astype(float).dtype
Out[34]: dtype('float64')
(2)shape/reshape
shape显示numpy矩阵的维度,reshape可以转换矩阵的维度
In [37]: test_shape = np.arange(10)
In [38]: test_shape
Out[38]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [39]: test_shape.shape # 显示shape信息
Out[39]: (10,)
In [40]: test_reshape = test_shape.reshape((2, 5))
In [41]: test_reshape
Out[41]:
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
In [43]: test_reshape.shape
Out[43]: (2, 5) # 现在的shape是(2,5)
到此numpy基本的信息已经介绍了,下篇继续写numpy的其它特性