引言:之前做神经网络,对数据计算和展示都是现学现用,不会就查,未曾系统地学习过python数据分析库等,所以受到过很大的阻力,准备花个两天时间系统地学习一下,下面仅简单列出基本函数的使用
一.numpy基本函数
# 创建 ndarray 数组对象 x = np.array(object, dtype)
ndarray对象属性
.ndim |
维度的数量 |
.shape |
ndarray对象维度,对矩阵,(m,n) |
.size |
ndarray对象元素个数,对矩阵,相当于.shape的n*m |
.dtype |
ndarray对象的元素类型 |
.itemsize |
ndarray对象中每个元素大小,以字节为单位 |
ndarray数组创建
np.arange(n,dtype = 'float32') | 返回ndarray类型,元素从0到n-1,且元素为float32类型 |
np.ones(shape) |
根据shape生成一个全1数组 |
np.zeros(shape) | 根据shape生成一个全0数组 |
np.full(shape,val) | 根据shape生成一个每个元素值都是val的数组 |
np.eye(n) | 创建n*n单位矩阵 |
np.ones_like(a) | 根据数组a的形状生成一个全1数组 |
np.zeros_like(a) | 根据数组a的形状生成一个全0数组 |
np.full_ike(a,val) | 根据数组a的形状生成一个每个元素值都是val的数组 |
np.linspace(1,10,4,endpoint = False) | 根据起止数据等间距地填充数据,形成数组,endpoint代表10是否作为生成元素 |
np.concatenate() | 将多个数组合并成一个新数组 |
ndarray数组变换
a.reshape(shape) | 不改变数组元素,返回一个shape形状的数组 |
a.resize(shape) | 类似于.reshape,修改原数组 |
a.swapaxes(ax1,ax2) | 将数组n个维度中两个维度进行调换 |
a.flatten() | 对数组进行降维,返回折叠后的一维数组 |
a.astype(new_type) | 返回一个以new_type数据类型的数组 |
a.tolist() | 返回一个由数组转换成的列表 |
ndarray数组运算
np.square(x) | 各元素的平方 |
np.sqrt(x) | 各元素的平方根 |
np.abs(x) | 各元素的绝对值 |
np.log(x) np.log10(x) np.log2(x) |
各元素的对数运算 |
np.ceil(x) np.floor(x) |
分别对应各元素的向上取整和向下取整 |
np.rint(x) | 各元素四舍五入的值 |
np.modf(x) | 各元素小数和证书部分以两个独立数组形式返回 |
np.cos(x) np.cosh(x) ..... |
各元素普通型和双曲型三角函数 |
np.exp(x) | 各元素的指数值 |
np.sign(x) | 各元素的符号值,分别对应1(+),0,-1(-) |
np.dot(x) | 矩阵运算 |
+ - * / ** | 两数组各元素进行对应运算 |
> < >= <= == != | 算术比较,产生布尔型数组 |
np.mod(x,y) | 元素级的模运算 |
np.copysign(x,y) | 数组y中各元素值符号赋值给数组x对应元素 |
np.maximum(x,y) np.minimum(x,y) |
元素级的最大值/最小值计算 |
Numpy数据存储
# csv文件写入 np.savetxt(frame, array, fmt = '%.18e', delimiter = None) frame:文件,字符串等,可以是.gz,bz2的压缩文件 array:存入的数组 fmt:元素的格式 delimiter:分割字符串,默认空格 # csv文件读入 np.loadtxt(frame, dtype = np.float, delimiter = None, unpack = False) dtype:读取数据类型 unpack:若为True,分列读取 # 多维数据的存储 a.tofile(frame, sep = '', format = '%s') sep:分割字符串,若为空写入二进制 format:写入文件类型 # 多维数据的读取 np.fromfile(frame, dtype = float, count = -1, sep = '') count:读入元素个数,-1表示整个文件 # numpy 便捷文件存取,无需考虑数据类型和维度 np.save(fname, array) np.load(fname)Numpy随机数
rand(d0,d1,...,dn) | 根据d0-dn创建随机数数组,服从[0,1)上的均匀分布 |
randn(d0,d1,...,dn) | 根据d0-dn创建随机数数组,服从标准正太分布 |
randint(low,high,shape) | 根据shape双肩随机整数数组,范围是[low,high) |
seed(s) | 随机数种子 |
shuffle(a) | 根据数组a的第一轴进行随机排列,改变数组a |
permutation(a) | 根据数组a的第一轴产生一个新的乱序数组,不改变数组a |
choice(a,size,replace,p) | 从一维数组a中以概率p抽取元素,形成size形状新数组,replace表示是否可以重用元素,默认True |
uniform(low,high,size) | 产生具有均匀分布的数组,low起始值,high结束值,size形状 |
normal(loc,scale,size) | 产生具有正太分布的数组,loc均值,scale标准差,size形状 |
poisson(lam,size) | 产生具有泊松分布的数组,lam随机事件发生率,size形状 |
Numpy统计函数
sum(a,axis = None) | 根据给定轴axis计算数组a相关元素之和 |
mean(a,axis = None) |
根据给定轴axis计算数组a相关元素的期望 |
average(a,axis = None,weights = None) | 根据给定轴axis计算数组a相关元素的加权平均值 |
std(a,axis = None) | 根据给定轴axis计算数组a相关元素的标准差 |
var(a,axis = None) | 根据给定轴axis计算数组a相关元素的方差 |
min(a) max(a) |
计算数组a中元素的最小值、最大值 |
argmin(a) argmax(a) |
计算数组a中元素最小值、最大值的降一维后下标 |
unravel_index(index,shape) | 根据shape将一维下表index转换成多维下表 |
ptp(a) | 计算数组a中元素最大值与最小值的差 |
median(a) | 计算数组a中元素的中位数 |
Numpy梯度函数
np.gradient(f) |
计算数组f中元素的梯度,当f为多维时,返回每个维度梯度 |
二.Matplotlib简单用法
基本绘图函数
plt.plot(x,y,format_string,**kwargs) | 分别对应X轴数据(可选),Y轴数据,控制曲线的格式字符串,更多(x,y,format_string) |
plt.xlabel() plt.ylabel() |
设置横/纵坐标的文本标签 |
plt.show() | 显示绘制图形 |
plt.title() | 对图形整体增加文本标签 |
plt.text() | 在任意位置增加文本 |
plt.annotate(s,xy = arrow_crd,xytext = text_crd,arrowprops = dict) | 在图形中增加带箭头的注解。s表注解字符串,xy对应箭头位置,xytext对应文本位置,arrowprops定义显示属性 |
plt.axis([-1, 10, 0, 6]) | 横/纵坐标的显示范围 |
plt.grid(True) | 是否显示网格曲线 |
plt.savefig(name,dip) | 保存绘制图像文件 |
a = np.arange(0,5,0.02) plt.plot(a, np.cos(2 * np.pi * a), 'r--') plt.xlabel('横轴',fontproperties = 'SimHei',fontsize = 25, color = 'blue') plt.title(r'正弦波 $y = cos(2\pi x)$',fontproperties = 'SimHei',fontsize = 25) plt.annotate(r'$\mu = 100$',xy = (2,1),xytext = (3,1.5),arrowprops = dict(facecolor = 'black',shrink = 0.1, width = 2)) plt.axis([-1,6,-2,2]) plt.grid(True) plt.show()
pyplot的中文显示
# 同时修改坐标系值的字体类型 import matplotlib matplotlib.rcParams['font.family'] = 'SimHei' # 中文黑体 # 仅修改坐标轴标签的字体类型 plt.xlabel('横轴',fontproperties = 'SimHei',fontsize = 20) plt.ylabel('横轴',fontproperties = 'SimHei',fontsize = 20)
font.family |
显示字体的名字 |
font.style | 字体风格,'normal' 或 'italic' |
font.size | 字体大小 |
pyplot图像区域划分
plt.subplot() | 绘制子区域 |
plt.subplot2grid() | 高级绘制子区域 |
plt.subplot(221) plt.subplot2grid((3,3),(1,0),colspan = 2) # GridSpec 类用法 import matplotlib.gridspec as gridspec gs = gridspec.GridSpec(3,3) x = plt.subplot(gs[0,:-1])
pyplot其他图形的绘制
plt.plot(x,y,fmt,...) | 绘制坐标图 |
plt.boxplot(data,notch,position) | 绘制箱形图 |
plt.bar(left,height,width,bottom) | 绘制条形图 |
plt.barh(width,bottom,left,height) | 绘制横向条形图 |
plt.polar(theta,r) | 绘制极坐标图 |
plt.pie(data,explode) | 绘制饼图 |
plt.psd(x,NFFT = 256,pad_to,Fs) | 绘制功率谱密度图 |
plt.specgram(x,NFFT = 256,pad_to,F) | 绘制谱图 |
plt.cohere(x,y,NFFT = 256,Fs) | 绘制X-Y相关性函数 |
plt.scatter(x,y) | 绘制散点图 |
plt.step(x,y,where) | 绘制步阶图 |
plt.hist(x,bins,normed) | 绘制直方图 |
plt.contour(X,Y,Z,N) | 绘制等值图 |
plt.vlines() | 绘制垂直图 |
plt.stem(x,y,linefmt,markerfmt) | 绘制柴火图 |
plt.plot_date() |
绘制数据日期 |
# 常用图形绘制实例 import numpy as np import matplotlib.pyplot as plt # 散点图 fig, ax = plt.subplots() ax.plot (np.random.randn(100), np.random.randn(100), 'o') ax.set_title('Scatter') plt.show() # 饼图绘制 labels = 'PYTHON','JAVA','C++','PHP' sizes = [15,30,45,10] explode = (0,0,0.1,0) plt.pie(sizes,explode = explode,labels = labels,autopct = '%1.1f%%',shadow = False, startangle = 90) plt.axis('equal') plt.show() # 直方图绘制 np.random.seed(0) mu, sigma = 100, 20 # 均值,标准差 a = np.random.normal(mu, sigma, size = 100) plt.hist(a, 50, normed = 1, histtype = 'stepfilled', facecolor = 'b',alpha = 0.75) plt.show() # 极坐标 N = 30 theta = np.linspace(0, 2 * np.pi, N, endpoint = False) radii = 10 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) ax = plt.subplot(111, projection = 'polar') bars = ax.bar(theta, radii, width = width, bottom = 0) # 上色 for r,bar in zip(radii, bars): bar.set_facecolor(plt.cm.viridis(r / 10.)) bar.set_alpha(0.5) plt.show()
三.pandas库
Series类型创建
import pandas as pd # 默认索引 a1 = pd.Series([5,4,3,2]) # 自定义索引 a2 = pd.Series([5,4,3,2],index = ['a','b','c','d']) # 以标量创建 a3 = pd.Series(25,index = ['a','b','c']) # 以字典类型创建 a4 = pd.Series({'a':5,'b':4,'c':3}) a5 = pd.Series({'a':5,'b':4,'c':3,'d':2}, index = ['d','b','c','q']) # 以ndarray类型创建 a6 = pd.Series(np.arange(5)) a7 = pd.Series(np.arange(5),index = np.arange(9,4,-1))
Series类型基本操作
b = pd.Series([5,4,3,2],index = ['a','b','c','d']) # 分别获得索引和数据 b.index output:Index(['a', 'b', 'c', 'd'], dtype='object') b.values output:array([5, 4, 3, 2], dtype=int64) # 两种形式的索引方式并存,但不能同时使用 b['b'] output:4 b[1] output:4 'c' in b output:True b.get('z',100) output:100 b[['c','b','a']] output:c 3 b 4 a 5 dtype: int64 b[['c','b',0]] output:c 3.0 b 4.0 0 NaN dtype: float64 b[:3] output:a 5 b 4 c 3 dtype: int64 b[b > b.median()] output:a 5 b 4 dtype: int64
Series类型的name属性
b = pd.Series([5,4,3,2],index = ['a','b','c','d']) b.name = 'Series' b.index.name = 'index' output:index a 5 b 4 c 3 d 2 Name: Series, dtype: int64
DataFrame类型创建
import pandas as pd # Series类型创建 dt = {'one':pd.Series([5,4,3,2],index = ['a','b','c','d']), 'two':pd.Series([8,7,6],index = ['a','c','d'])} d1 = pd.DataFrame(dt) d2 = pd.DataFrame(dt,index = ['b','c','d'],columns = ['one','two']) # 字典类型创建 dl = {'one':[1,2,3,4], 'two':[9,8,7,6]} d3 = pd.DataFrame(dl, index = ['a','b','c','d']) # 数据的提取 d3['one'] d3.ix['b'] d3['one']['b'] # 先列后行
Pandas数据类型操作
reindex(index = None, columns = None,fill_value,method, limit,copy) | index,columns:新的行列索引,fill_value:填充缺失位置值,method:填充方法,ffill当前值向前填充,bfill向后填充,limit:最大填充量,copy:默认True生成新的对象 |
dl = {'one':[1,2,3,4], 'two':[9,8,7,6]} d = pd.DataFrame(dl, index = ['a','b','c','d']) newc = d.columns.insert(1,'three') newd = d.reindex(columns = newc, fill_value = 200)
索引类型常用函数(pandas默认行)
.append(idx) | 连接另外一个index对象,产生新的index对象 |
.diff(idx) | 计算差集,产生新的index对象 |
.intersection(idx) | 计算交集,产生新对象 |
.union(idx) | 计算并集 |
.delete(loc) | 删除loc位置出的元素 |
.insert(loc,e) | 在loc位置增加一个元素e |
.drop() | 删除指定的行或列 |
算术运算
.add(d, **argws) | 加法运算 |
.sub(d, **argws) | 减法运算 |
.mul(d, **argws) | 乘法运算 |
.div(d, **argws) | 除法运算 |
数据排序
.sort_index(axis = 0, ascending = True) | 在指定轴上根据索引进行排序,默认升序 |
.sort_values(axis = 0, ascending = True) | 在指定轴上根据数值进行排序,默认升序 |
Pandas统计分析函数
.sum() | 按列计算数据综合 |
.count() | 非NaN值得数量 |
.mean() .median() |
分别计算算术平均值,中位数 |
.var() .std() |
分别计算方差,标准差 |
.min() .max() |
分别计算最小值,最大值 |
.argmin() .argmax() |
针对自动索引,分别计算最大、最小值所在位置的索引 |
.idxmin() .idxmax() |
针对自定义索引,分别计算最大、最小值所在位置的索引 |
.describe() | 对各列统计数据的汇总 |
.cov() | 计算协方差矩阵 |
.corr() | 计算相关系数矩阵 |