《人工智能基础及应用(Python 微课版)》程序代码汇 王军选 第2-7章 数据处理与分析-自然语言处理_第1页
《人工智能基础及应用(Python 微课版)》程序代码汇 王军选 第2-7章 数据处理与分析-自然语言处理_第2页
《人工智能基础及应用(Python 微课版)》程序代码汇 王军选 第2-7章 数据处理与分析-自然语言处理_第3页
《人工智能基础及应用(Python 微课版)》程序代码汇 王军选 第2-7章 数据处理与分析-自然语言处理_第4页
《人工智能基础及应用(Python 微课版)》程序代码汇 王军选 第2-7章 数据处理与分析-自然语言处理_第5页
已阅读5页,还剩78页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第2章数据处理与分析【例2.1】array举例importnumpyasnpa=np.array([1,2,3])b=np.array([[1,2],[3,4]])#多于一个维度c=np.array([1,2,3,4,5],ndmin=2)#最小维度d=np.array([1,2,3],dtype=complex)#dtype参数print(a,b,c,d)【例2.2】查看ndarray对象举例importnumpyasnp#引入numpy库a2=np.array(([1,5,3,4,5],[6,2,7,9,5]))#创建二维的narray对象print(type(a2))#a的类型是数组print(a2)print(a2.dtype)#查看a5数组中每个元素的类型print(a2.shape)#查看数组的行列,返回行列的元组,5行5列print(a2.shape[1])#查看a5的列数print(a2.ndim)print(a2.T)#简单转置矩阵ndarray【例2.3】索引和切片举例importnumpyasnpa=np.array([[1,2,3,4,5],[6,7,8,9,10]])print(a)print(a[:])#选取全部元素print(a[1])#选取行为1的全部元素print(a[0:1])#截取[0,1)的元素print(a[1,2:5])#截取第2行第[2,5)的元素[8910]print(a[1,:])#截取第2行,返回[678910]print(a[1,2])#截取行号为1,列号为2的元素8print(a[1][2])#截取行号为1,列号为2的元素8,与上面的等价print(a[a>3])#截取矩阵a中大于3的数,范围的是一维数组b=np.arange(10)#[0123456789]x=slice(2,7,2)print(b[x])【例2.4】numpy.zeros举例importnumpyasnp#1)默认浮点x=np.zeros(5)print(x)#2)整数:下面三种写法方法1:y=np.zeros(5,dtype=int)#Python原生int方法2:y=np.zeros(5,dtype=_)#NumPy的默认整数类型(64位)方法3:y=np.zeros(5,dtype=32)#明确32位整数print(y)#3)自定义结构化dtypez=np.zeros((2,2),dtype=[('x','i4'),('y','i4')])print(z)【例2.5】numpy.ones举例importnumpyasnp#默认为浮点数x=np.ones(5)print(x)#自定义类型x=np.ones([2,2],dtype=int)print(x)【例2.6】numpy.diag举例importnumpyasnp#默认为浮点数x=np.diag([1,2,3])print(x)【例2.7】arange举例importnumpyasnpa=np.arange(10)#利用arange函数创建数组print(a)a5=np.arange(1,2,0.1)print(a5)【例2.8】linspace举例importnumpyasnpa=np.linspace(0,1,10)#从0开始到1结束,共10个数的等差数列print(a)【例2.9】logspace举例importnumpyasnpa=np.logspace(0,1,5)#生成首位是10的0次方,末位是10的1次方,含5个数的等比数列print(a)【例2.10】数组维度变换举例importnumpyasnpa=np.array([1,2,3,4,5,6])b=a.reshape(2,3)c=a.reshape((2,3))d=np.reshape(a,(2,3))print(a)#输出[123456]print(b)#输出[[123][456]]print(c)#输出[[123][456]]print(d)#输出[[123][456]]a1=np.array([[1,2,3],[4,5,6]])b1=a.flatten()c1=a.ravel()#多维转一维d1=a.reshape(-1)#参数为-1,表示数组的维度通过数据本身判断print(a1)#输出[[123][456]]print(b1)#输出[123456]print(c1)#输出[123456]print(d1)#输出[123456]a2=np.array([[1,2,3],[4,5,6]])b2=a.transpose()c2=a.Td2=a.swapaxes(0,1)e2=np.transpose(a,(1,0))print(a2)#输出[[123][[456]]print(b2)#输出[[14][25][36]]print(c2)#输出[[14][25][36]]print(d2)#输出[[14][25][36]]print(e2)#输出[[14][25][36]]【例2.11】数组拼接举例importnumpyasnpa=np.array([[1,2,3],[4,5,6]])b=np.arange(2,8).reshape(2,3)c1=np.concatenate([a,b],axis=0)c2=np.vstack([a,b])d1=np.concatenate([a,b],axis=1)d2=np.hstack([a,b])print(a)#输出[[123][456]]print(b)#输出[[234][567]]print(c1)#输出[[123][456][234][567]]print(c2)#输出[[123][456][234][567]]print(d1)#输出[[123234][456567]]print(d2)#输出[[123234][456567]]【例2.12】数组分割举例importnumpyasnpa=np.arange(1,19).reshape(6,3)b,c=np.split(a,[4],axis=0)d,e=np.vsplit(a,[4])print(a)#输出[[123][456][789][101112][131415][161718]]print(b)#前4个样本为1个数组[[123][456][789][101112]]print(c)#余下的样本为1个数组[[131415][161718]]print(d)#前4个样本为1个数组[[123][456][789][101112]]print(e)#余下的样本为1个数组[[131415][161718]]【例2.13】数组复制举例importnumpyasnpa=np.array([1,2,3])b=ac=a[:]d=np.copy(a)print(bisa,cisa,disa)#输出TrueFalseFalsed[0]=10print(a,d)#输出[123][1023]c[0]=100print(a,c)#输出[10023][10023]【例2.14】通过list创建Series对象importpandasaspdseries=pd.Series([1,2,3])print(series)【例2.15】通过字典创建Series对象importpandasaspddict={'a':0,'b':1,'c':5}print(pd.Series(dict))【例2.16】通过ndarray创建Seriesimportpandasaspdimportnumpyasnpprint('通过ndarray创建的Series为:\n',pd.Series(np.arange(3),index=['a','b','c'],name='ndarray'))【例2.17】访问Series的属性importpandasaspdseries1=pd.Series([1,2,3,10])print("series1:\n{}\n".format(series1))print("series1.values:{}\n".format(series1.values))#Series中的数据print("series1.index:{}\n".format(series1.index))#Series中的索引print("series1.shape:{}\n".format(series1.shape))#Series中的形状print("series1.ndim:{}\n".format(series1.ndim))#Series中的维度【例2.18】访问Seriesimportpandasaspdseries2=pd.Series([1,2,3,4,5,6,7],index=["C","D","E","F","G","A","B"])#通过索引位置访问Series数据子集print("series2位于第1位置的数据为:",series2[0])#通过索引名称(标签)也可以访问Series数据print("Eis{}\n".format(series2["E"]))【例2.19】

更新Seriesimportpandasaspdlist1=[1,2,3,4,5]series1=pd.Series(list1,index=['a','b','c','d','e'],name='list')print("series1:\n{}\n".format(series1))series1['a']=3print('更新后的Series1为:\n',series1)【例2.20】

追加Seriesimportpandasaspdlist1=[2,3,10]series1=pd.Series(list1,index=['a','b','c'],name='list')print("series1:\n{}\n".format(series1))series2=pd.Series([5],index=['f'])result=pd.concat([series1,series2])print('合并后:\n',result)【例2.21】删除Series元素举例importpandasaspdlist1=[0,1,2,3,10]series1=pd.Series(list1,index=['a','b','c','d','e'],name='list')print("series1:\n{}\n".format(series1))#1)不修改原Seriess2=series1.drop('a')#或series1.drop('a',inplace=False)print('删除索引a后(返回新对象):\n',s2)#2)原地删除series1.drop('e',inplace=True)print('再删除索引e后(原对象已改变):\n',series1)【例2.22】通过字典创建DataFrameimportpandasaspddata={'name':['张三','李四','王五'],'sex':['female','male','female'],'age':[23,21,20]}df=pd.DataFrame(data,columns=['name','age','sex','address'])print('通过dict创建的DataFrame为:\n',df)【例2.23】通过list创建DataFrame举例importpandasaspdlist5=[[0,5],[1,6],[2,7],[3,8],[10,9]]print('通过list创建的DataFrame为:\n',pd.DataFrame(list5,index=['a','b','c','d','e'],columns=['col1','col5']))【例2.24】通过Series创建DataFrame举例importpandasaspdnoteSeries=pd.Series(["C","D","E","F","G","A","B"])weekdaySeries=pd.Series(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],index=[1,2,3,4,5,6,7])df10=pd.DataFrame([noteSeries,weekdaySeries])print("df10:\n{}\n".format(df10))【例2.25】访问DataFrame的属性importpandasaspddf=pd.DataFrame({'col1':[0,1,2,3,4],'col2':[5,6,7,8,9]},index=['a','b','c','d','e'])print('DataFrame的Index为:',df.index)#Index(['a','b','c','d','e'],dtype='object')print('DataFrame的列标签为:',df.columns)#Index(['col1','col2'],dtype='object')print('DataFrame的列数据类型为:',df.dtypes)#col1int64print('DataFrame的轴标签为:',df.axes)print('DataFrame的维度为:',df.ndim)#2print('DataFrame的形状为:',df.shape)#(5,2)print('DataFrame的数据为:',df.values)print('DataFrame的元素个数为:',df.size)#10【例2.26】选取行列数据importpandasaspddata={'name':['张三','李四','王五'],'sex':['female','male','female'],'age':[23,21,20],'address':['西安市','郑州市','北京市']}df=pd.DataFrame(data,columns=['name','age','sex','address'],index=['a','b','c'])print('默认返回前5行数据为:\n',df.head())print('返回后2行数据为:\n',df.tail(2))print(df[1:2])df2=df.iloc[[0,2],[1,3]]#提取不连续行和列的数据,提取第0,2行,第1,3列的数据print(df2)df3=df.iat[1,1]#提取某一个数据,提取第2行,第2列数据(默认从0开始)print(df3)w1=df['name']print(w1)w2=df[df['age']>21]print(w2)w3=df.query('age==21')print(w3)【例2.27】更新DataFrame举例importpandasaspddf=pd.DataFrame({'col1':[0,1,2,3,4],'col5':[5,6,7,8,9]},index=['a','b','c','d','e'])print('DataFrame为:\n',df)更新列df['col1']=[10,11,12,13,14]print('更新列后的DataFrame为:\n',df)【例2.28】插入DataFrame举例importpandasaspddf3=pd.DataFrame({"note":["C","D","E","F","G","A","B"],"weekday":["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]})print("df3:\n{}\n".format(df3))df3["No."]=pd.Series([1,2,3,4,5,6,7])#采用赋值的方法插入列print("df3:\n{}\n".format(df3))【例2.29】删除DataFrame举例importpandasaspddf=pd.DataFrame({'col1':[0,1,2,3,10],'col5':[5,6,7,8,9]},index=['a','b','c','d','e'])df['col3']=[10,19,2,19,20]print('插入列后的DataFrame为:\n',df)df.drop(['col3'],axis=1,inplace=True)print('删除col3列DataFrame为:\n',df)df.drop('a',axis=0,inplace=True)print('删除a行DataFrame为:\n',df)【例2.30】df.replace()举例importpandasaspd#1)先把数据改成“混合型”:字符串列保留字符串,数值列直接给数字df=pd.DataFrame({'名称':['产品1','产品2','产品3','产品10','产品5','产品6','产品7','产品110'],'数量':[0.1,0.7,0.110,0.10,0.7,None,0.76,0.2110],'金额':[0,0.10110,0.33,None,0.710,0,0,0.22],'合计':[None,0.37,0.2110,None,0.57,None,0,0.06],})print('原始df:\n',df,'\n')#2)整表替换:把“缺失值”先统一换成0df1=df.fillna(0)print('df1(缺失值->0):\n',df1,'\n')#3)只替换“名称”这一列里的部分字符串df['名称']=df['名称'].str.replace('产品','product',regex=False)print('仅替换“名称”列后的df:\n',df,'\n')#4)对“合计”列做字典替换,并直接改原表df['合计'].replace({None:0.11111},inplace=True)#这里None就是原来的NaNprint('替换“合计”列后的df:\n',df)【例2.31】df[].map举例importpandasaspdimportnumpyasnpdata={'姓名':['周元哲','潘婧','詹涛','王颖','李震'],'性别':['1','0','0','0','1']}df=pd.DataFrame(data)df['成绩']=[91,56,82,67,77]print(df)defgrade(x):ifx>=90:return'优秀'elifx>=80:return'良好'elifx>=70:return'中等'elifx>=60:return'及格'else:return'不及格'df['等级']=df['成绩'].map(grade)print(df)【例2.32】pd.merge(df1,df2)举例importpandasaspdleft=pd.DataFrame({'key':['K0','K1','K2','K3'],'A':['A0','A1','A2','A3'],'B':['B0','B1','B2','B3']})right=pd.DataFrame({'key':['K0','K1','K2','K3'],'C':['C0','C1','C2','C3'],'D':['D0','D1','D2','D3']})result=pd.merge(left,right,on='key')#on参数传递的key作为连接键print("left:\n{}\n".format(left))print("right:\n{}\n".format(right))print("merge:\n{}\n".format(result))【例2.33】bine_first(df2)举例importnumpyasnpimportpandasaspda=pd.Series([np.nan,2.5,np.nan,3.5,10.5],index=['f','e','d','c','b'])b=pd.Series([1,np.nan,3,10,5],index=['f','e','d','c','b'])print(a)print(b)c=bine_first(a)print(c)【例2.34】数据离散化举例importpandasaspdages=[20,7,37,31,68,105,52]bins=[0,18,35,50,60]cuts=pd.cut(ages,bins)print(cuts)【例2.35】df.fillna(num)举例fromnumpyimportnanasNaNimportpandasaspddf1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]])print("df1:\n{}\n".format(df1))print(df1.notnull())#notnull函数判断是否有空值df2=df1.fillna(50)print("df2:\n{}\n".format(df2))【例2.36】df.dropna()举例fromnumpyimportnanasNaNimportpandasaspddf1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]])print("df1:\n{}\n".format(df1))df2=df1.dropna()print("df2:\n{}\n".format(df2))【例2.37】重复值清洗举例importpandasaspd#导入Pandas库data=pd.DataFrame({'a':[2,2,2,2],'b':[2,2,2,2],'c':[2,2,1,3],'d':[1,1,3,3]})print(data)isDuplicated=data.duplicated()#判断重复数据记录print("重复值为:\n",isDuplicated)#打印输出print("删除重复值后:\n",data.drop_duplicates())data.drop_duplicates(subset=['a','b'],keep='first',inplace=True)print("有条件的删除重复值后:\n",data)【例2.38】稀疏矩阵举例fromscipy.sparseimportcoo_matriximportnumpyasnp#创建一个稀疏矩阵A=coo_matrix([[1,2,0],[0,0,3],[4,0,11]])print("原始稀疏矩阵A:")print(A)#转化为普通矩阵C=A.todense()#转化为普通矩阵print("转换为普通矩阵C:")print(C)#传入一个(data,(row,col))的元组来构建稀疏矩阵#注意:I和J的索引值不能超过矩阵的维度I=np.array([0,2,1,0])#行索引,确保索引值小于矩阵的行数J=np.array([0,3,1,2])#列索引,确保索引值小于矩阵的列数data=np.array([4,11,7,9])#对应的数据A_new=coo_matrix((data,(I,J)),shape=(4,4))#指定矩阵维度为4x4print("通过(data,(row,col))构建的稀疏矩阵A_new:")print(A_new)【例2.39】创建CSR矩阵。importnumpyasnpfromscipy.sparseimportcsr_matrixarr=np.array([0,0,0,0,0,1,1,0,2])print(csr_matrix(arr))【例2.40】创建CSR矩阵。importnumpyasnpfromscipy.sparseimportcsr_matrixarr=np.array([[0,0,0],[0,2,3],[1,0,2]])print(csr_matrix(arr).data)print(csr_matrix(arr).count_nonzero())【例2.41】矩阵运算举例fromscipyimportlinalgimportnumpyasnpA=np.matrix('[1,2;3,4]')print(A)print(A.T)#转置矩阵print(A.I)#逆矩阵print(linalg.inv(A))#逆矩阵【例2.42】线性方程组求解fromscipyimportlinalgimportnumpyasnpa=np.array([[1,3,5],[2,5,-1],[2,4,7]])b=np.array([10,6,4])x=linalg.solve(a,b)print(x)【例2.43】非线性方程组求解举例fromscipy.optimizeimportfsolvefrommathimportsindeff(x):

x0,x1,x2=x.tolist()

return[5*x1+3,4*x0*x0-2*sin(x1*x2),x1*x2-1.5]#f计算方程组的误差,[1,1,1]是初始值result=fsolve(f,[1,1,1])

#输出方程组的解print(result)#输出误差print(f(result))【例2.44】求的最小值fromscipy.optimizeimportminimizeimportnumpyasnp#计算1/x+x的最小值deffun(args):a=argsv=lambdax:a/x[0]+x[0]returnvif__name__=="__main__":args=(1)#ax0=np.asarray((2))#初始猜测值res=minimize(fun(args),x0,method='SLSQP')print(res.fun)print(res.success)print(res.x)【例2.45】最小二乘法举例importnumpyasnpfromscipy.optimizeimportleastsqimportmatplotlib.pyplotasplt#推荐用plt,而不是pylabfrommatplotlibimportrcParamsimportmatplotlibmatplotlib.use('TkAgg')#——中文显示&负号————————————————————————rcParams['font.sans-serif']=['SimHei']#黑体,Windows自带rcParams['axes.unicode_minus']=False#正常显示负号#——拟合函数————————————————————————————————deffunc(x,p):"""A*sin(2πkx+θ)"""A,k,theta=preturnA*np.sin(2*np.pi*k*x+theta)deferrf(p,y,x):"""残差"""returny-func(x,p)#——构造数据————————————————————————————————x=np.linspace(0,-2*np.pi,100)#注意:终点是-2πA,k,theta=10,0.34,np.pi/6#真实参数y0=func(x,[A,k,theta])#真值y1=y0+2*np.random.randn(len(x))#加噪声#——拟合————————————————————————————————————p0=[7,0.2,0]#初值plsq,cov,info,mesg,ier=leastsq(errf,p0,args=(y1,x),full_output=True)#——打印结果————————————————————————————————print("真实参数:",[A,k,theta])print("拟合参数:",plsq)#——画图————————————————————————————————————plt.figure()plt.plot(x,y0,'r-',label='真实数据')plt.plot(x,y1,'g.',label='带噪声的实验数据',markersize=3)plt.plot(x,func(x,plsq),'b--',label='拟合曲线')plt.legend()plt.tight_layout()plt.show()第3章数据可视化【例3.1】Matplotlib绘图举例importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnp#让中文正常显示matplotlib.rcParams['font.family']='KaiTi'matplotlib.rcParams['axes.unicode_minus']=False#解决负号显示成方块的问题#π×2的正确写法是2*np.pi或2*math.pix=np.arange(0,2*np.pi,0.05)y=np.sin(x)fig=plt.figure()ax=fig.add_axes([0.1,0.1,0.8,0.8])#2.坐标轴范围别贴着边界,留一点边距ax.plot(x,y)ax.set_title('正弦曲线示例')ax.set_xlabel('横轴值')ax.set_ylabel('纵轴值')#y轴范围应该是[-1,1],而不是[1,1]ax.set_xlim(0,2*np.pi)ax.set_ylim(-1,1)plt.show()【例3.2】subplot举例importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnpfig=plt.figure(num=1,figsize=(4,4))plt.subplot(221)#画布分为2x2的区域plt.plot([1,2,3,4],[1,2,3,4])plt.subplot(222)plt.plot([1,2,3,4],[2,2,3,4])plt.subplot(223)plt.plot([1,2,3,4],[1,2,2,4])plt.subplot(224)plt.plot([1,2,3,4],[1,2,3,3])plt.show()【例3.3】add_subplot举例importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnp#让中文正常显示fig=plt.figure(num=1,figsize=(4,4))ax1=fig.add_subplot(221)#画布分为2x2的区域rect=plt.Rectangle((0.1,0.2),0.3,0.6,color='r')#创建一个矩形,参数:(x,y),width,heightax1.add_patch(rect)#将形状添加到子图上ax2=fig.add_subplot(222)circ=plt.Circle((0.5,0.3),0.2,color='r',alpha=0.3)#创建一个椭圆,参数:中心点,半径,默认圆形随窗口大小进行长宽压缩ax2.add_patch(circ)#将形状添加到子图上ax3=fig.add_subplot(223)pgon=plt.Polygon([[0.2,0.2],[0.65,0.6],[0.2,0.6]])#创建一个多边形,参数:每个顶点坐标ax3.add_patch(pgon)#将形状添加到子图上fig.canvas.draw()#子图绘制plt.show()【例3.4】折线图举例importnumpyasnpimportmatplotlibmatplotlib.use('TkAgg')#强制走Tk图形后端,保证弹出独立窗口frommatplotlibimportpyplotaspltx=np.arange(1,11)y=2*x*x+5plt.title("plotfigure")plt.xlabel("xaxis")plt.ylabel("yaxis")plt.plot(x,y)plt.show()【例3.5】散点图举例importnumpyasnpimportmatplotlib.pyplotaspltx=np.arange(1,10)#产生测试数据y=xfig=plt.figure()ax1=fig.add_subplot(111)ax1.set_title('ScatterPlot')#设置标题plt.xlabel('X')#设置X轴标签plt.ylabel('Y')#设置Y轴标签ax1.scatter(x,y,c='r',marker='o')#画散点图plt.legend('x1')#设置图标plt.show()#显示所画的图【例3.6】饼状图举例importmatplotlib.pyplotaspltimportnumpyasnplabels=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']data=np.random.rand(7)*100plt.pie(data,labels=labels,autopct='%1.1f%%')plt.axis('equal')plt.legend()plt.show()【例3.7】条形图举例importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnpplt.rcParams['font.size']=10#全局字号plt.rcParams['axes.unicode_minus']=False#解决负号显示方框labels=['Apple','Banana','Orange','Pear','Watermelon']sales=[83,61,55,47,38]fig,ax=plt.subplots(figsize=(6,4))bars=ax.bar(labels,sales,color='tomato',edgecolor='k',linewidth=0.8)#数值标签置顶forbinbars:height=b.get_height()ax.text(b.get_x()+b.get_width()/2,height+1,f'{height}',ha='center',va='bottom')ax.set_ylabel('Sales/boxes')ax.set_title('Fruitsales')plt.tight_layout()plt.show()【例3.8】箱线图举例importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnp#1.造数据np.random.seed(42)data=np.concatenate([np.random.normal(100,10,90),np.random.normal(150,15,10)])#2.画图fig,ax=plt.subplots(figsize=(6,3))bp=ax.boxplot(data,vert=False,patch_artist=True,boxprops=dict(facecolor='lightblue'),showmeans=False,widths=0.3)#3.关键数值q1,q2,q3=np.percentile(data,[25,50,75])iqr=q3-q1whis_lo=q1-1.5*iqrwhis_hi=q3+1.5*iqr#4.标注(纯英文,位置用y=0.15保证在图内)style=dict(fontsize=9,va='center',ha='center')y_txt=0.15ax.text(q1,y_txt,f'Q1\n{q1:.1f}',**style)ax.text(q2,y_txt,f'Q2\n{q2:.1f}',**style)ax.text(q3,y_txt,f'Q3\n{q3:.1f}',**style)#IQR箭头ax.annotate('',xy=(q3,0.35),xytext=(q1,0.35),arrowprops=dict(arrowstyle='<->',color='red'))ax.text((q1+q3)/2,0.4,f'IQR={iqr:.1f}',color='red',**style)#须线ax.text(whis_lo,y_txt,f'Lower\n{whis_lo:.1f}',**style)ax.text(whis_hi,y_txt,f'Upper\n{whis_hi:.1f}',**style)ax.set_xlim(50,180)ax.set_yticks([])ax.set_title('BoxplotElements')plt.tight_layout()plt.show()【例3.9】面积图举例#0.统一导入importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnpplt.rcParams['font.size']=10plt.rcParams['axes.unicode_minus']=Falsex=np.linspace(0,10,200)y=2+np.sin(x)*np.exp(-x*0.2)days=np.arange(1,8)#一周7天A=np.array([20,22,18,25,30,28,32])B=np.array([15,19,16,22,24,26,29])C=np.array([10,12,14,15,18,20,23])labels=['ProductA','ProductB','ProductC']colors=['#ff7f0e','#2ca02c','#1f77b4']plt.figure(figsize=(6,4))plt.stackplot(days,A,B,C,labels=labels,colors=colors,alpha=0.8)plt.legend(loc='upperleft')plt.title('StackedAreaChart')plt.xlabel('Day')plt.ylabel('Sales')plt.tight_layout()plt.show()【例3.10】环形图举例#0.统一导入importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnpplt.rcParams['font.size']=10plt.rcParams['axes.unicode_minus']=False#内环:大类outer_labels=['Mobile','Desktop']outer_sizes=[60,40]outer_colors=['#ff9f43','#0984e3']#外环:细分inner_labels=['iOS','Android','Win','macOS']inner_sizes=[35,25,22,18]inner_colors=['#feca57','#ff7675','#74b9ff','#a29bfe']fig,ax=plt.subplots(figsize=(6,6),subplot_kw=dict(aspect='equal'))#外环(细分数)ax.pie(inner_sizes,labels=inner_labels,colors=inner_colors,autopct='%1.1f%%',startangle=90,radius=1,#外半径wedgeprops=dict(width=0.3,edgecolor='w'))#内环(大类)ax.pie(outer_sizes,labels=outer_labels,colors=outer_colors,autopct='%1.1f%%',startangle=90,radius=0.7,#内半径wedgeprops=dict(width=0.3,edgecolor='w'))#中心白圆centre_circle=plt.Circle((0,0),0.4,fc='white')fig.gca().add_artist(centre_circle)ax.set_title('Device&OSSplitDonutChart')plt.tight_layout()plt.show()【例3.11】三维图两种创建方式方法一:利用关键字frommatplotlibimportpyplotaspltfrommpl_toolkits.mplot3dimportAxes3D#定义坐标轴fig=plt.figure()ax1=plt.axes(projection='3d')#ax=fig.add_subplot(111,projection='3d')#可以绘制多个子图方法二:利用三维轴方法frommatplotlibimportpyplotaspltfrommpl_toolkits.mplot3dimportAxes3D#定义图像和三维格式坐标轴fig=plt.figure()ax2=Axes3D(fig)【例3.12】绘制三角螺旋线importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnpplt.rcParams['font.size']=10plt.rcParams['axes.unicode_minus']=False#1.创建图+3D子图fig=plt.figure(figsize=(6,4))ax=fig.add_subplot(111,projection='3d')#2.数据zline=np.linspace(0,15,1000)xline=np.sin(zline)yline=np.cos(zline)#3.绘图ax.plot3D(xline,yline,zline,'gray')#4.显示plt.show()【例3.13】绘制三维散点的数据importmatplotlib.pyplotaspltimportnumpyasnpax=plt.axes(projection='3d')zdata=15*np.random.random(100)xdata=np.sin(zdata)+0.1*np.random.randn(100)ydata=np.cos(zdata)+0.1*np.random.randn(100)ax.scatter3D(xdata,ydata,zdata,c=zdata,cmap='Reds')【例3.14】绘制三维等高线图frommpl_toolkitsimportmplot3dimportmatplotlib.pyplotaspltimportnumpyasnpdeff(x,y):returnnp.sin(np.sqrt(x**2+y**2))x=np.linspace(-6,6,30)y=np.linspace(-6,6,30)X,Y=np.meshgrid(x,y)Z=f(X,Y)fig=plt.figure()ax=plt.axes(projection='3d')ax.contour3D(X,Y,Z,50,cmap='binary')ax.set_xlabel('x')ax.set_ylabel('y')ax.set_zlabel('z')#俯仰角设为60度,把方位角调整为35度ax.view_init(60,35)【例3.15】直方图举例importnumpyasnpimportmatplotlibmatplotlib.use('TkAgg')#强制Tk后端,独立窗口frommatplotlibimportpyplotaspltimportseabornassnsimportwarningswarnings.filterwarnings('ignore')#可选:样式sns.set_style('darkgrid')plt.rcParams['figure.figsize']=(8,4)plt.rcParams['figure.dpi']=100plt.rcParams['axes.unicode_minus']=False#生成100个成标准正态分布的随机数x=np.random.normal(size=100)#kde=True进行核密度估计sns.distplot(x,kde=True,hist=False)#hist为FALSE,直接绘制密度图而没有直方图plt.show()【例3.16】核密度图举例importnumpyasnpimportmatplotlibmatplotlib.use('TkAgg')#强制Tk后端,独立窗口frommatplotlibimportpyplotaspltimportseabornassnsfig,ax=plt.subplots()np.random.seed(4)#可复现Gaussian=np.random.normal(0,1,1000)#标准正态数据#1.直方图(密度尺度)ax.hist(Gaussian,bins=25,histtype="stepfilled",density=True,alpha=0.6,color='skyblue')#2.KDE曲线sns.kdeplot(Gaussian,shade=True,ax=ax,color='navy')ax.set_title('StandardNormalDistribution')ax.set_xlabel('Value')ax.set_ylabel('Density')plt.tight_layout()plt.show()【例3.17】小提琴图举例importnumpyasnpimportmatplotlibmatplotlib.use('TkAgg')#强制Tk后端,独立窗口frommatplotlibimportpyplotaspltimportseabornassnsimportwarningswarnings.filterwarnings('ignore')#可选:样式sns.set_style('darkgrid')plt.rcParams['figure.figsize']=(8,4)plt.rcParams['figure.dpi']=100plt.rcParams['axes.unicode_minus']=False#加载irisiris=sns.load_dataset('iris')#画小提琴图sns.violinplot(data=iris,palette='hls')plt.title('IrisFeaturesDistribution')plt.xlabel('Features')plt.ylabel('Value')#关键:弹出窗口plt.show()【例3.18】绘制热力图importnumpyasnpimportmatplotlibmatplotlib.use('TkAgg')#强制Tk后端,独立窗口frommatplotlibimportpyplotaspltimportseabornassnsimportwarningswarnings.filterwarnings('ignore')#可选:样式sns.set_style('darkgrid')plt.rcParams['figure.figsize']=(8,4)plt.rcParams['figure.dpi']=100plt.rcParams['axes.unicode_minus']=Falseimportnumpyasnp;np.random.seed(0)importseabornassns;sns.set()importmatplotlib.pyplotaspltuniform_data=np.random.rand(10,12)f,ax=plt.subplots(figsize=(9,6))ax=sns.heatmap(uniform_data)plt.show()【例3.19】等高线举例importseabornassnsimportnumpyasnpimportmatplotlibmatplotlib.use('TkAgg')#强制走Tk图形后端,保证弹出独立窗口frommatplotlibimportpyplotasplt#1.加载官方示例数据(新版Seaborn自带)penguins=sns.load_dataset("penguins")#2.去掉缺失值,防止KDE警告penguins=penguins.dropna(subset=["bill_length_mm","bill_depth_mm"])#3.绘制二维KDE联合图g=sns.jointplot(x="bill_length_mm",y="bill_depth_mm",kind="kde",data=penguins,fill=True,#填充颜色更直观thresh=0.05#去掉极低密度边缘)g.fig.suptitle("PenguinBillDimensions–KDEJointPlot",y=1.02)plt.show()第4章数据社交网【例4.1】无向图importmatplotlibmatplotlib.use('TkAgg')importmatplotlib.pyplotaspltimportnumpyasnpimportnetworkxasnxG=nx.Graph()#创建一个空的无向图G.add_edge(1,2,weight=4.2)#添加一个从节点1到节点2的边,权重为4.2G.add_nodes_from([3,4])#添加多个节点nx.draw(G,with_labels=True)plt.show()【例4.2】有向图importnetworkxasnximportmatplotlibimportmatplotlib.pyplotasplt#若PyCharm不弹图,强制使用TkAgg后端matplotlib.use('TkAgg')DG=nx.DiGraph()#创建空有向图DG.add_edge(1,2)#1->2DG.add_edge(3,4)#3->4#画出来plt.figure(figsize=(3,2))pos=nx.spring_layout(DG,seed=2025)#固定布局,方便复现nx.draw(DG,pos,with_labels=True,node_color='skyblue',node_size=800,arrowsize=15,font_size=10)plt.title('PyCharm下最简单的有向图示例')plt.tight_layout()plt.show()【例4.3】多重图importnetworkxasnximportmatplotlibimportmatplotlib.pyplotaspltmatplotlib.use('TkAgg')#1.创建空的多重图G=nx.MultiGraph()#2.添加节点G.add_nodes_from([1,2,3])#3.添加多条平行边G.add_edge(1,2,key='a',weight=7)G.add_edge(1,2,key='b',weight=10)G.add_edge(1,3)G.add_edge(2,3)#4.访问特定边print("边(1,2,key='a')的属性:",G[1][2]['a'])#{'weight':7}#5.获取1-2之间所有边的keyprint("1-2的所有key:",list(G.get_edge_data(1,2).keys()))#dict_keys(['a','b'])#6.删除key='a'的边G.remove_edge(1,2,key='a')#7.重新确认剩余keyprint("删除后1-2的key:",list(G.get_edge_data(1,2).keys()))#只剩['b']#8.绘图pos=nx.spring_layout(G,seed=2025)#固定布局,便于复现plt.figure(figsize=(4,3))nx.draw_networkx_nodes(G,pos,node_color='lightblue',node_size=800)nx.draw_networkx_labels(G,pos,font_size=10,font_family='SimHei')#为平行边手动做弯曲,避免重叠nx.draw_networkx_edges(G,pos,width=2,edge_color='gray',connectionstyle='arc3,rad=0.15',#弯曲,让平行边错开arrows=False)plt.axis('off')plt.tight_layout()plt.show()【例4.4】节点属性importnetworkxasnx#创建一个无向图G=nx.Graph()#添加节点G.add_node('A')G.add_node('B')G.add_node('C')#添加边G.add_edge('A','B')G.add_edge('A','C')#使用add_node方法添加属性G.add_node('A',color='red',size=10)G.add_node('B',color='blue',size=20)#使用nodes[node]['attr']方式添加属性G.nodes['C']['color']='green'G.nodes['C']['size']=15#获取节点'A'的属性node_A_attrs=G.nodes['A']print(f"Node'A'attributes:{node_A_attrs}")#获取节点'B'的颜色属性color_B=G.nodes['B']['color']print(f"Node'B'color:{color_B}")#获取节点'C'的大小属性size_C=G.nodes['C']['size']print(f"Node'C'size:{size_C}")【程序运行结果】Node'A'attributes:{'color':'red','size':10}Node'B'color:blueNode'C'size:15【例4.5】节点操作importnetworkxasnximportmatplotlib.pyplotaspltimportmatplotlibmatplotlib.use('TkAgg')G=nx.Graph()#建立一个空的无向图GG.add_node('a')#添加一个节点G.add_nodes_from(['b','c','d','e'])#加点集合nx.add_cycle(G,['f','g','h','j'])#加环H=nx.path_graph(10)#返回

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论