1、NUMPY
NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。
NumPy 是一个运行速度非常快的数学库,主要用于数组计算,包含:
- 一个强大的N维数组对象 ndarray。
- 广播功能函数。
- 整合 C/C++/Fortran 代码的工具。
- 线性代数、傅里叶变换、随机数生成等功能。
Numpy的安装
-
使用已有的发行版本
-
使用 pip 安装
Numpy基本函数
.ndim :维度
.shape :各维度的尺度 (2,5)
.size :元素的个数 10
.dtype :元素的类型 dtype(‘int32’)
.itemsize :每个元素的大小,以字节为单位 ,每个元素占4个字节
ndarray数组的创建
np.arange(n) ; 元素从0到n-1的ndarray类型
np.ones(shape): 生成全1
np.zeros((shape), ddtype = np.int32) : 生成int32型的全0
np.full(shape, val): 生成全为val
np.eye(n) : 生成单位矩阵
np.ones_like(a) : 按数组a的形状生成全1的数组
np.zeros_like(a): 同理
np.full_like (a, val) : 同理
np.linspace(1,10,4): 根据起止数据等间距地生成数组
np.linspace(1,10,4, endpoint = False):endpoint 表示10是否作为生成的元素
np.concatenate():
numpy.empty
numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组:
numpy.empty(shape, dtype = float, order = 'C')
实例:
1 import numpy as np 2 x = np.empty([3,2], dtype = int) 3 print (x)
numpy.asarray
numpy.asarray 类似 numpy.array,但 numpy.asarray 参数只有三个,比 numpy.array 少两个。
实例:
1 import numpy as np 2 x = [1,2,3] 3 a = np.asarray(x, dtype = float) 4 print (a)
NumPy 从数值范围创建数组
numpy.arange
numpy 包中的使用 arange 函数创建数值范围并返回 ndarray 对象,函数格式如下:
numpy.arange(start, stop, step, dtype)
NumPy 切片和索引
ndarray对象的内容可以通过索引或切片来访问和修改,与 Python 中 list 的切片操作一样。
ndarray 数组可以基于 0 - n 的下标进行索引,切片对象可以通过内置的 slice 函数,并设置 start, stop 及 step 参数进行,从原数组中切割出一个新数组。
NUMPY 统计函数
NumPy 提供了很多统计函数,用于从数组中查找最小元素,最大元素,百分位标准差和方差等。 函数说明如下:
numpy.amin() 用于计算数组中的元素沿指定轴的最小值。
numpy.amax() 用于计算数组中的元素沿指定轴的最大值。
numpy.ptp()函数计算数组中元素最大值与最小值的差(最大值 - 最小值)。
numpy.median() 函数用于计算数组 a 中元素的中位数(中值)
numpy.mean() 函数返回数组中元素的算术平均值。
numpy.average() 函数根据在另一个数组中给出的各自的权重计算数组中元素的加权平均值。
numpy 矩阵库
1 import numpy as np 2 3 a = np.arange(12).reshape(3,4) 4 5 print ('原数组:') 6 print (a) 7 print ('\n') 8 9 print ('转置数组:') 10 print (a.T)
输出结果:
scipy
scipy是基于numpy的一个科学计算库,它提供了更多的高级函数和模块,涵盖了优化,积分,插值,傅里叶变换,信号处理,图像处理,常微分方程等领域。scipy的主要功能有:
使用scipy.optimize模块进行优化,如使用scipy.optimize.minimize(),scipy.optimize.curve_fit(),scipy.optimize.root()等函数。
使用scipy.integrate模块进行积分,如使用scipy.integrate.quad(),scipy.integrate.odeint(),scipy.integrate.solve_ivp()等函数。
使用scipy.interpolate模块进行插值,如使用scipy.interpolate.interp1d(),scipy.interpolate.splrep(),scipy.interpolate.splev()等函数。
使用scipy.fftpack模块进行傅里叶变换,如使用scipy.fftpack.fft(),scipy.fftpack.ifft(),scipy.fftpack.fftshift()等函数。
使用scipy.signal模块进行信号处理,如使用scipy.signal.convolve(),scipy.signal.correlate(),scipy.signal.firwin(),scipy.signal.lfilter()等函数。
使用scipy.ndimage模块进行图像处理,如使用scipy.ndimage.imread(),scipy.ndimage.rotate(),scipy.ndimage.zoom(),scipy.ndimage.filters.gaussian_filter()等函数。
Pandas
Pandas常见用途有:
- 数据清洗:加载、清洗和转换数据,处理缺失值和异常值。
- 数据分析:基于Series和DataFrame进行统计分析、聚合和数据切片。
- 时间序列处理:支持日期范围生成、频率转换、移动窗口统计等时间序列操作。
Matplotlib
Matplotlib广泛用于:
- 折线图:展示趋势和变化。
- 散点图:显示数据点之间的关系和分布。
- 直方图:展示数据分布和频数。
- 饼图:用于表示数据在整体中的占比情况。