一、NumPy
NumPy(Numerical Python)是Python语言的一个扩展程序库,支持了大量的维度数组和矩阵计算,同时也针对数组运算提供了大量的数学函数库。广泛应用于矩阵运算、线性代数、傅立叶变换、随机数生成等领域。
二、基本数据类型
NumPy支持的数据类型比Python内置的类型要多,基本上可以和C语言的数据类型对应,其中部分类型对应为Python内置的类型。常用NumPy基本类型如下:
# string
array_string=np.array(['1.24','2.6','21'], dtype=np.string_)
array_string.astype(float)
# print result
array([1.24, 2.6, 21.])
注意:由于NumPy的字符串数据类型大小是固定的,当发生截取时,不会告警。所以使用numpy.string_要小心,不要发生截取。实在用NumPy处理不了的字符串数据,可以用pandas,其提供了非数值数据的便利处理方法。第二,调用astype方法会创建一个新的数组,无论astype里的数据类型跟原始dtype是否一样。
三、NumPy数组初始化
import numpy as np
np.zeros(20, dtype=int)
# 创建一个长度为20的数组,数组的值都为0
# print
# array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
np.ones((4,5), dtype=float)
# 创建一个4*5的浮点数类型数组,数组的值都为1.
# print
# array([[1., 1., 1., 1., 1.],
# [1., 1., 1., 1., 1.],
# [1., 1., 1., 1., 1.],
# [1., 1., 1., 1., 1.]])
np.full((4,5), 3.14)
# 创建一个4*5的浮点数类型数组,数组的值都为3.14
# print
# array([[3.14, 3.14, 3.14, 3.14, 3.14],
# [3.14, 3.14, 3.14, 3.14, 3.14],
# [3.14, 3.14, 3.14, 3.14, 3.14],
# [3.14, 3.14, 3.14, 3.14, 3.14]])
np.arange(0, 20, 2)
# 创建一个整型数组,数组的值是一个线性序列,从0开始,到20结束,步长为2
# print
# array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
p.random.random((4,4))
# 创建一个4*4数组,其值为0-1间均分分配的随机数
# print
# array([[0.06616471, 0.18139292, 0.29060494, 0.2100059 ],
# [0.30988499, 0.02720308, 0.18864994, 0.62882524],
# [0.27220117, 0.28404628, 0.63963573, 0.46723886],
# [0.59130974, 0.42247367, 0.61229801, 0.0567741 ]])
p.random.normal(0, 1, (4,4))
# 创建一个4*4数组,其值为均值为0,方差为1的正态分布产生的随机数
# print
# array([[ 0.88720589, -1.62490681, 0.20583656, -2.08164876],
# [-0.706591 , -0.15754023, 0.85172636, 0.65038692],
# [-0.55309543, 0.76123212, -0.3306992 , 0.57460791],
# [ 1.08167741, -1.32120106, -1.33066866, -0.71509059]])
np.random.randint(0, 20, (4,4))
# 创建一个4*4数组,其值为[0, 20)间的随机整数
# print
# array([[ 6, 10, 8, 5],
# [ 9, 3, 15, 10],
# [ 1, 18, 2, 15],
# [16, 10, 9, 9]])
# np.random.randint的上下限相等时,回报错
>>> np.random.randint(20,20)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 992, in mtrand.RandomState.randint
ValueError: Range cannot be empty (low >= high) unless no samples are taken
np.eye(5)
# 创建一个5*5的单位矩阵
# print
# array([[1., 0., 0., 0., 0.],
# [0., 1., 0., 0., 0.],
# [0., 0., 1., 0., 0.],
# [0., 0., 0., 1., 0.],
# [0., 0., 0., 0., 1.]])
np.empty(5)
# 创建一个由5个整数组成的数组,其值是内存空间中的任意值
# print
# array([1., 1., 1., 1., 1.])
四、NumPy数组和list的互相转化
>>> import numpy as np
>>> list = [1,2,3,4]
>>> array = np.array(list)
>>> array
array([1, 2, 3, 4])
>>> list2 = array.tolist()
>>> list2
[1, 2, 3, 4]
引用
【1】NumPy Data types:https://numpy.org/doc/stable/user/basics.types.html
【2】https://www.runoob.com/numpy/numpy-dtype.html
【3】NumPy 源代码:https://github.com/numpy/numpy
【4】SciPy 官网:https://www.scipy.org/
【5】SciPy 源代码:https://github.com/scipy/scipy
【6】Matplotlib 官网:https://matplotlib.org/
【7】Matplotlib 源代码:https://github.com/matplotlib/matplotlib