《Python语言程序设计》课件-第八章(英文课件)_第1页
《Python语言程序设计》课件-第八章(英文课件)_第2页
《Python语言程序设计》课件-第八章(英文课件)_第3页
《Python语言程序设计》课件-第八章(英文课件)_第4页
《Python语言程序设计》课件-第八章(英文课件)_第5页
已阅读5页,还剩258页未读 继续免费阅读

下载本文档

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

文档简介

PythonLanguageProgramming1ComprehensiveCase1SynthesisCase1:ElectricityBiddingDataReadingandProcessing2DataAnalysisTrilogy.(1)Datasourcereading-completethereadingofbadbehaviorinformationdatainthefile"1_biddingdatacase.xlsx"throughprogramming;(2)Datafilteringandmerging-filteringandmergingofreaddata.(3)Dataoutput-thedataobtainedinthepreviousstepisoutputtoformanewfile.CaseBackground.StateGridCorporationinordertoensuretheexcellentqualityofmaterials,equipment,services,suppliermanagementsystem,thereisapenaltyforbadbehavior,poorperformance,qualityproblems,etc.,supplierswillbeincludedinthepenaltyforbadbehavior.Oncethesupplierhasbadbehaviorpenalty,thenwillnotparticipateinthecorrespondingbidding.3SynthesisCase1:ElectricityBiddingDataReadingandProcessing1.SourcedatareadingReadthedatafromthetwoworksheets"Case1_SupplierBidData"and"Case1_BadBehaviorData"inthefile"1_BidDataCase.xlsx",andrecordthemastable_aandtable_brespectively.Thecodesareasfollows:12345678Table_a_name="1_BidDataCase"table_a_path=table_a_name+'.xlsx'Sheet_a_name="Case1_SupplierBiddingData"Table_a=pd.read_excel(table_a_path,sheet_name=sheet_a_name,converters={'Suppliercode':str}).dropna(axis=1,how='all')Table_b_name="1_BidDataCase"table_b_path=table_b_name+".xlsx"Sheet_b_name="Case1_BadBehaviorData"Table_b=pd.read_excel(table_b_path,sheet_name=sheet_b_name,converters={'Suppliercode':str})4SynthesisCase1:ElectricityBiddingDataReadingandProcessing2.ScreeningandconsolidationofdataNeedtoscreenoutbadbehaviordatainthebiddingdata,accordingtotheStateGridCorporation'spenaltyrequirements,ifthebadbehaviordata,processingrangefor"allcategories",thenthesupplierallbidscannotparticipatein,thatis,inthebiddingdata,needtoexcludeallthesupplier'sdata;ifthebadbehaviordata,processingrangeforthespecificcategories,thenthesuppliercannotparticipateinspecificcategoriesofbidding,thatis,inthebiddingdata,theneedtoexcludethespecificsupplierspecificcategoriesofbiddingdata.1234567#ProcessingallcategoriesTable_b_tmp=table_tmp[table_tmp['processingrange']=='allcategories']Table_c=table_a.merge(table_b_tmp,on=['suppliercode'],suffixes=('','_y'))table_total=table_c[table_a.columns]#DealingwithspecificcategoriesTable_b_tmp=table_tmp[table_tmp['processingrange']!='Allcategories']Table_c=table_a.merge(table_b_tmp,on=['suppliercode','packagenumber','bidsectionname'],suffixes=('','_y'))table_specific=table_c[table_a.columns]5SynthesisCase1:ElectricityBiddingDataReadingandProcessing3.DataoutputReadtheoutputfileinstep3andoutputthedatatobeexcludedandthedatafornormalparticipationinbidding.1234table_w=pd.concat([table_total,table_specific],axis=0)Table_w.to_excel('BadBehaviorBiddingData.xlsx')table_y=table_a.drop(labels=table_w.index,axis=0)Table_y.to_excel('normalbiddata.xlsx')Python语言程序设计6《综合案例1》综合案例1:电力招投标数据读取与处理7数据分析三部曲:(1)数据源读取——通过编程完成对文件“1_投标数据案例.xlsx”中不良行为信息数据的读取;(2)数据筛选与合并——对读取的数据进行筛选与合并;(3)数据输出——对上一步获取的数据进行输出,形成新文件。案例背景:国网公司为了保证物资、设备、服务的优良品质,对供应商管理体系中有一个不良行为的处罚,对履约不好、有质量问题等的供应商,会纳入不良行为处罚。一旦供应商存在不良行为处罚,那么就不参与相应的招投标。8综合案例1:电力招投标数据读取与处理1.源数据读取读取文件“1_投标数据案例.xlsx”中的“案例1_供应商投标数据”和“案例1_不良行为数据”两个工作表的数据,分别记为table_a和table_b。代码如下:12345678table_a_name="1_投标数据案例"table_a_path=table_a_name+'.xlsx'sheet_a_name="案例1_供应商投标数据"table_a=pd.read_excel(table_a_path,sheet_name=sheet_a_name,converters={'供应商代号':str}).dropna(axis=1,how='all')table_b_name="1_投标数据案例"table_b_path=table_b_name+".xlsx"sheet_b_name="案例1_不良行为数据"table_b=pd.read_excel(table_b_path,sheet_name=sheet_b_name,converters={'供应商代号':str})9综合案例1:电力招投标数据读取与处理2.数据筛选与合并需要在投标数据中筛选出不良行为的数据,根据国网公司的处罚要求,如果不良行为数据中,处理范围为“所有品类”,那么该供应商所有投标都不能参与,即在投标数据中,需要剔除该供应商的所有数据;如果不良行为数据中,处理范围为特定的品类,那么该供应商不能参与特定品类的投标,即在投标数据中,需要剔除特定该供应商特定品类的投标数据。1234567#处理所有品类的table_b_tmp=table_tmp[table_tmp['处理范围']=='所有品类']table_c=table_a.merge(table_b_tmp,on=['供应商代号'],suffixes=('','_y'))table_total=table_c[table_a.columns]#处理特定品类的table_b_tmp=table_tmp[table_tmp['处理范围']!='所有品类']table_c=table_a.merge(table_b_tmp,on=['供应商代号','包号','标段名称'],suffixes=('','_y'))table_specific=table_c[table_a.columns]10综合案例1:电力招投标数据读取与处理3.数据输出读取第3步输出的文件,输出需剔除的数据和正常参与招投标的数据。1234table_w=pd.concat([table_total,table_specific],axis=0)table_w.to_excel('不良行为投标数据.xlsx')table_y=table_a.drop(labels=table_w.index,axis=0)table_y.to_excel('正常投标数据.xlsx')PythonLanguageProgramming11ComprehensiveCase212SynthesisCase2:PowerDataAnalysisandVisualizationFirstreadtherequiredpowerdata,basedonthesupplierbiddingprice,forabnormaldatacleaning,andthenthroughthepivottableontheminimumvalueofpowerquotes,themaximumvalueandtheaveragevalueofstatisticalanalysis,andfinallythroughthevisualizationofthedata.1.SourcedatareadingReadthedataof"Case2_SupplierBidQuotationWorksheet"inthefile"1_BidDataCase.xlsx",andassignthevalueasp_data.Thecodeisasfollows.1p_data=pd.read_excel(r'./1_biddingdatacase.xlsx',sheet_name='Case2_supplierbiddingquotation')13SynthesisCase2:PowerDataAnalysisandVisualization2.DatacleansingInordertobetteranalyzethedata,thesourcedataneedstobecleaned.Forthedataof"supplierbiddingquotation"inthiscase,usethe3deltaprincipletodealwithoutliers.Bycalculatingtheaveragevalueuandstandarddeviationdeltaofthebiddingprice,usethe3deltaprincipletocleantheinvaliddata.Thecodesareasfollows:123456P_data['Bidprice(tenthousandyuan)'].hist(bins=20)U=p_data['Bidprice(tenthousandyuan)'].mean()#AverageofbidpriceDelta=p_data['Bidprice(tenthousandyuan)'].std()#Standarddeviationofbidpricea=u-3*deltab=u+3*deltaP_data=p_data[(p_data['tenderprice(tenthousandyuan)']<=b)]14SynthesisCase2:PowerDataAnalysisandVisualization3.PivottablesStatisticalanalysisofquantitiesandminimum,maximumandaveragevaluesofquotationsbysub-tendernameandpackagenumber,andfinallyapivottable.12345678#Pt=pd.pivot_table(p_data,index=['Nameofbiddivision','PackageNo.'],columns=[],values=['Bidprice(tenthousandyuan)','Biddivisionnumber'],aggfunc={'Bidprice(tenthousandyuan)':np.max,'Bidprice(tenthousandyuan)':np.min,'Bidprice(tenthousandyuan)':np.average,'Biddivisionnumber':'count'},margins=True)Pt1=pd.pivot_table(p_data,index=['Nameofbiddivision','PackageNo.'],columns=[],values=['Bidprice(tenthousandyuan)','Biddivisionnumber'],aggfunc={'Bidprice(tenthousandyuan)':np.max,'Biddivisionnumber':'count'},margins=False)Pt2=pd.pivot_table(p_data,index=['Nameofbiddivision','PackageNo.'],columns=[],values=['Bidprice(tenthousandyuan)','Biddivisionnumber'],aggfunc={'Bidprice(tenthousandyuan)':np.min,'Biddivisionnumber':'count'},margins=False)Pt3=pd.pivot_table(p_data,index=['Nameofbiddivision','PackageNo.'],columns=[],values=['Bidprice(tenthousandyuan)','Biddivisionnumber'],aggfunc={'Bidprice(tenthousandyuan)':np.average,'Biddivisionnumber':'count'},margins=False)Pt1.to_excel(r'max.xlsx')Pt2.to_excel(r'min.xlsx')Pt3.to_excel(r'average.xlsx')print(pt1,pt2,pt3)15SynthesisCase2:PowerDataAnalysisandVisualization4.DatavisualizationandpresentationVisualizethecodeasfollows.123456789101112131415importpandasaspdimportmatplotlib.pyplotaspltfrompylabimportmplN=input("Filename:")nn=n+".xlsx"mpl.rcParams['font.sans-serif']=['SimHei']mpl.rcParams['axes.unicode_minus']=Falsehouse=pd.read_excel(nn)Mean_price_district=house['Bidprice(tenthousandyuan)']mean_price_district.plot(kind='bar')print(mean_price_district)plt.title(n)Plt.xlabel(u"biddivisionname")Plt.ylabel(u"bidprice(10000yuan)")plt.show()Python语言程序设计16《综合案例2》17综合案例2:电力数据分析与可视化首先读取需要的电力数据,依据供应商投标报价,针对异常数据进行清洗,再通过透视表对电力报价最小值、最大值以及平均值统计分析,最后通过可视化展示数据。1.源数据读取读取文件“1_投标数据案例.xlsx”中的“案例2_供应商投标报价工作表”数据,赋值为p_data。代码如下:1p_data=pd.read_excel(r'./1_投标数据案例.xlsx',sheet_name='案例2_供应商投标报价')18综合案例2:电力数据分析与可视化2.数据清洗为更好地对数据进行分析,需要对源数据进行清洗。针对本案例“供应商投标报价”数据,使用3delta原则处理离群值,通过计算投标价格的平均值u,标准差delta,以3delta原则来清洗无效数据。代码如下:123456p_data['投标价格(万元)'].hist(bins=20)u=p_data['投标价格(万元)'].mean()#投标价格的平均值delta=p_data['投标价格(万元)'].std()#投标价格的标准差a=u-3*deltab=u+3*deltap_data=p_data[(p_data['投标价格(万元)']<=b)]19综合案例2:电力数据分析与可视化3.数据透视表按照分标名称、包号进行数量以及报价最小值、最大值以及平均值的统计分析,最后得出透视表。12345678#pt=pd.pivot_table(p_data,index=['分标名称','包号'],columns=[],values=['投标价格(万元)','分标编号'],aggfunc={'投标价格(万元)':np.max,'投标价格(万元)':np.min,'投标价格(万元)':np.average,'分标编号':'count'},margins=True)pt1=pd.pivot_table(p_data,index=['分标名称','包号'],columns=[],values=['投标价格(万元)','分标编号'],aggfunc={'投标价格(万元)':np.max,'分标编号':'count'},margins=False)pt2=pd.pivot_table(p_data,index=['分标名称','包号'],columns=[],values=['投标价格(万元)','分标编号'],aggfunc={'投标价格(万元)':np.min,'分标编号':'count'},margins=False)pt3=pd.pivot_table(p_data,index=['分标名称','包号'],columns=[],values=['投标价格(万元)','分标编号'],aggfunc={'投标价格(万元)':np.average,'分标编号':'count'},margins=False)pt1.to_excel(r'最大值.xlsx')pt2.to_excel(r'最小值.xlsx')pt3.to_excel(r'平均值.xlsx')print(pt1,pt2,pt3)20综合案例2:电力数据分析与可视化4.数据可视化展示可视化代码如下:123456789101112131415importpandasaspdimportmatplotlib.pyplotaspltfrompylabimportmpln=input("文件名:")nn=n+".xlsx"mpl.rcParams['font.sans-serif']=['SimHei']mpl.rcParams['axes.unicode_minus']=Falsehouse=pd.read_excel(nn)mean_price_district=house['投标价格(万元)']mean_price_district.plot(kind='bar')print(mean_price_district)plt.title(n)plt.xlabel(u"分标名称")plt.ylabel(u"投标价格(万元)")plt.show()PythonLanguageProgramming21NumpyInstallationandCommonFunctions2Knowledgepoints22[numpyinstallationandcommonfunctions]Knowledgepoint1Numery(shortforNumericalPython)isaveryfastmathematicallibrary,mainlyusedforarraycalculation,including:ApowerfulN-dimensionalarrayobjectThebroadcastfunctionfunction,theToolsforintegratingC/C++/Fortrancodelinearalgebra,Fouriertransforms,randomnumbergeneration,andotherfunctions2Knowledgepoints23ThearrayobjectisanN-dimensionalarrayobject,whichisaseriesofdatasetsofthesametype.Theelementsinthecollectionareindexedstartingwiththe0subscript.Theinteriorofthearrayconsistsofthefollowing:

Apointertodata(apieceofdatainmemoryoramemory-mappedfile).

Datatypeordtype,whichdescribesthelatticeoffixedsizevaluesinthearray.

Atuplerepresentingtheshapeofanarray,representingthesizeofeachdimension.

Aspantuple,inwhichtheintegerreferstothenumberofbytesthatneedtobe"crossed"toadvancetothenextelementofthecurrentdimension.1.ndarray[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints24Arrayproperty:arrayisamultidimensionalarraythatstoresasingledatatype.2.ArrayattributesGenusExplanationndimReturnsint.RepresentsthedimensionofanarrayshapeReturntuple.Representsthesizeofthearray.Forthematrixwithnrowsandmcolumns,theshapeis(n,m)sizeReturnsint.Representsthetotalnumberofelementsofanarray,equaltotheproductofarrayshapesdtypeReturndatatype.DescribesthetypesofelementsinanarrayitemsizeReturnsint.Representsthesize(inbytes)ofeachelementofthearray.[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints25Tocreateanarray,justcallthearrayfunctionofNumPy:2.ArrayattributesNameDescriptionobjectarraysornestedarraysdtypeDatatypeofthearrayelement,optionalcopyWhethertheobjectneedstobecopied,optionalorderCreatethearraystyle.Cistherowdirection,Fisthecolumndirection,andAisanydirection(default)subokwhichbydefaultreturnsanarrayofthesametypeasthebaseclassndminSpecifiestheminimumdimensionofthegeneratedarray[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints26[Example7-1]Createanarrayobject2.Arrayattributes1234Importnumpyasnp#ImportNumPylibrary

Arr1=np.array([1,2])#Onedimensionalarrayarr2=np.array([[1,2,3],[2,3,4]])arr3=np.array([[1,2],[2,3],[3,4],[4,5]])[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints27PracticalSkills[shape,dtype]2.Arrayattributes[Example]shape1Print("Arraydimensionis:",arr1.shape)Function:Viewthedimensionsofanarray.Foramatrix,nrowsandmcolumns[Example]dtype1Print("arraytype:",arr1.dtype)Function:Viewtheelementtypeofthearrayobject[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints28PracticalSkills[shape,dtype]2.Arrayattributes[Example]size1Print("Thenumberofarrayelementsis:",arr1.size)Function:Checkthenumberofelementsinanarray[Example]itemsize1Print("Thesizeofeachelementofthearrayis:",arr1.itemsize)Function:Viewthesizeofeachelementofthearray[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints293.

arangeGenerateanarrayaccordingtotherangespecifiedbystartandstopandthestepsetbystep.123importnumpyasnpx=np.arange(5,dtype=float)print(x)[Example7-2]Generateanarrayof0to4withthetypeoffloat.numpy.arange(start,stop,step,dtype)[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints303.

arange123importnumpyasnparr=np.arange(5)Print('arr[4]Theindexresultis:',arr[4])[Example7-3]One-dimensionalarrayindex123importnumpyasnparr=np.array([[1,2,9,0],[3,4,1,8],[4,2,8,5]])Print('Indexresultis:',arr[2,2:3])[Example7-4]Multidimensionalarrayindexingaccessingthearraybyindex[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints314.CreatingarrayobjectsCreatearraysandviewarraypropertiesIn[1]:Importnumpyasnp#ImportNumPylibraryArr1=np.array([1,2,3,4])#Createaone-dimensionalarrayPrint('Arraycreatedis:',arr1)Out[1]:Thearraycreatedis:[1234]In[2]:arr2=np.array([[1,2,3,4],[4,5,6,7],[7,8,9,10]])#Createtwo-dimensionalarraysPrint('Arraycreated:n',arr2)Out[2]:Thearraycreatedis.[[1234][4567][78910]]In[3]:Print('Arraydimension:',arr2.shape)#ViewthearraystructureOut[3]:Arraydimensionsare:(3,4)In[4]:Print('Arraydimension:',arr2.dtype)#ViewthearraytypeOut[4]:Thearraydimensionis:int32In[5]:Print('Numberofarrayelements:',arr2.size)#ViewthenumberofarrayelementsOut[5]:Numberofarrayelements:12In[6]:Print('Arrayelementsize:',arr2.itemsize)#ViewthesizeofeachelementofthearrayOut[6]:Thesizeofeachelementofthearrayis:4[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints324.CreatingarrayobjectsResettheshapeattributeofthearrayIn[7]:Arr2.shape=4,3#ResetshapePrint('rr2afterresettingtheshapeis:',arr2)Out[7]:Thearr2afterresettingtheshapedimensionis:[[123][445][677][8910]]CreateanarrayusingthearangefunctionIn[8]:Print('Thearraycreatedusingthearangefunctionis:n',np.arange(0,1,0.1))Out[8]:Thearraycreatedusingthearangefunctionis:[00.10.20.30.40.50.60.70.80.9][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints334.CreatingarrayobjectsCreateanarrayusingthelinspacefunctionIn[9]:Print('Thearraycreatedbyusingthelinspacefunctionis:',np.linspace(0,1,12))Out[9]:Thearraycreatedwiththelinspacefunctionis:[00.09090909…1.]UsethelogspacefunctiontocreateaproportionalseriesIn[10]:Print('Thearraycreatedbyusingthelogspacefunctionis:',np.logspace(0,2,20))Out[10]:Thearraycreatedwiththelogspacefunctionis:[11.274274991.62377674...,61.5848211178.47599704100.][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints344.CreatingarrayobjectsCreateanarrayusingthezerosfunctionIn[11]:Print('Arraycreatedwithzerosfunctionis:',np.zeros((2,3)))Out[11]:Thearraycreatedusingthezerosfunctionis:[[0.0.0.][0.0.0.]]CreateanarrayusingtheeyefunctionIn[12]:Print('Thearraycreatedwiththeeyefunctionis:',np.eye(3))Out[12]:Thearraycreatedusingtheeyefunctionis:[[1.0.0.][0.1.0.][0.0.1.]][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints354.CreatingarrayobjectsCreateanarrayusingthediagfunctionIn[13]:Print('Arraycreatedusingthediagfunctionis:',np.diag([1,2,3,4]))Out[13]:Thearraycreatedwiththediagfunctionis:[[1000][0200][0030][0004]]UsetheonesfunctiontocreateanarrayIn[14]:Print('Arraycreatedusingtheonesfunctionis:',np.ones((5,3)))Out[14]:Thearraycreatedwiththeonesfunctionis:[[1.1.1.][1.1.1.][1.1.1.][1.1.1.][1.1.1.]][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints365.ArraydatatypesNumPybasicdatatypeanditsvaluerange(onlyapartisdisplayed)TypeDescriptionboolBooleantypestoredwithonebit(valueisTRUEorFALSE)intiIntegerwhoseprecisionisdeterminedbytheplatform(usuallyint32orint64)int8Integersintherange-128to127int16Integersintherange-32768to32767int32

…………[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints375.Arraydatatypes(1)arraydatatypeconversionIn[15]:Print('conversionresult:',np.float64(42))#Integertofloating-pointconversionsOut[15]:Conversionresult:42.0In[16]:Print('conversionresult:',8(42.0))#Floating-pointtointegerconversionOut[16]:Theconversionresultis:42In[17]:Print('conversionresult:',np.bool(42))#IntegertoBooleanconversionOut[17]:Theconversionresultis:TrueIn[18]:Print('conversionresult:',np.bool(0))#IntegertoBooleanconversionOut[18]:Theconversionresultis:FalseIn[19]:Print('conversionresult:',np.float(True))#BooleantofloatingpointOut[19]:Conversionresult:1.0In[20]:Print('conversionresult:',np.float(False))#BooleantofloatingpointOut[20]:Conversionresult:0.0[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints385.Arraydatatypes(2)createthedatatypeToviewthedatatype,youcanviewitdirectlyorusethenumpy.dtypefunction.In[22]:Print('datatype:',df["name"])Out[22]:Thedatatypeis:<U40In[23]:Print('datatype:',np.dtype(df["name"]))Out[23]:Thedatatypeis:<U40[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints395.Arraydatatypes(2)createthedatatypeWhenusingthearrayfunctiontocreateanarray,thedatatypeofthearrayisfloatingpointbydefault.Ifyoucustomizethearraydata,youcanspecifythedatatypeinadvance.In[24]:itemz=np.array([("tomatoes",42,4.14),("cabbages",13,1.72)],dtype=df)Print('Userdefineddatais:',itemz)Out[24]:Theuser-defineddatais:[('tomatoes',42,4.14)('cabbages',13,1.72)][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints405.Arraydatatypes(3)generatingrandomnumbersGeneratingrandomnumberswithoutconstraintsIn[25]:Print('Thegeneratedrandomarrayis:',np.random.random(100))Out[25]:Thegeneratedrandomarrayis:[0.153431840.515815850.07228451...0.244183160.925105450.57507965]generatingrandomnumbersthatobeyauniformdistributionIn[26]:Print('Thegeneratedrandomarrayis:n',np.random.rand(10,5))Out[26]:Thegeneratedrandomarrayis.[[0.398304910.940113940.599749230.444538940.65451838]...[0.14685440.829729890.580111150.451576670.32422895]][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints415.Arraydatatypes(3)generatingrandomnumbersGeneraterandomnumbersthatobeyanormaldistributionIn[27]:Print('Thegeneratedrandomarrayis:n',np.random.randn(10,5))Out[27]:Thegeneratedrandomarrayis.[[-0.605719680.39034908-1.633155130.02783885-1.84139301]...,[-0.275004871.417112620.66359670.35486644-0.26700703]]Generatearandomnumberwithagivenupperandlowerrange,e.g.,createa2-row,5-columnarraywithaminimumvalueofnolessthan2andamaximumvalueofnomorethan10In[28]:Print('Thegeneratedrandomarrayis:',np.random.randint(2,10,size=[2,5]))Out[28]:

Thegeneratedrandomarrayis:[[666668][96684]][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints425.Arraydatatypes(3)generatingrandomnumbersRandomnumbergeneratingfunctioncommonlyusedinrandommodulefunctionExplanationseedDeterminetheseedoftherandomnumbergenerator.permutationReturnsarandompermutationofasequenceorreturnsarangeofrandompermutations.shuffleRandomizeasequence.binomialGeneratebinomiallydistributedrandomnumbers.normalGeneratenormal(Gaussian)distributedrandomnumbers.betaArandomnumberthatproducesabetadistribution.chisquareGeneraterandomnumberswithachi-squaredistribution.gammaArandomnumberthatproducesagammadistribution.uniformGeneraterandomnumbersuniformlydistributedin[0,1).[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints435.Arraydatatypes(4)transformingtheformofthearrayReshapethearrayshapeIn[43]:Arr=np.arange(12)#Createaone-dimensionalarrayPrint('Onedimensionalarraycreatedis:',arr)Out[43]:Theone-dimensionalarraycreatedis:[01234567891011]In[44]:Print('Thenewone-dimensionalarrayis:',arr.reshape(3,4))#SettheshapeofthearrayOut[44]:Thenewone-dimensionalarrayis:[[0123][4567][891011]]In[45]:Print('Arraydimensionis:',arr.reshape(3,4).ndim)#ViewthearraydimensionOut[45]:Arraydimensionsare:2[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints445.Arraydatatypes(4)transformingtheformofthearrayFlattenanarrayusingthetravelfunctionIn[46]:arr=np.arange(12).reshape(3,4)Print('2Darraycreatedis:',arr)Out[46]:Thetwo-dimensionalarraycreatedis.[[0123][4567][891011]]In[47]:Print('Arrayflattening:',arr.ravel())Out[47]:Thearrayisflattenedto:[01234567891011][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints455.Arraydatatypes(4)transformingtheformofthearrayFlattenanarrayusingtheflattenfunctionIn[48]:Print('Arrayflatteningis:',arr.flatten())#HorizontalflatteningOut[48]:Thearrayspreadis:[01234567891011]In[49]:Print('Arrayflattening:',arr.flatten('F'))#LongitudinalflatteningOut[49]:Thearrayspreadis:[04815926103711][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints465.Arraydatatypes(4)transformingtheformofthearraycombinatorialarraysUsethehstackfunctiontorealizearrayhorizontalcombination:np.hstack((arr1,arr2))Usevstackfunctiontorealizearrayverticalcombination:np.vstack((arr1,arr2))Useconcatenatefunctiontorealizehorizontalcombinationofarrays:np.concatenate((arr1,arr2),axis=1)Useconcatenatefunctiontorealizeverticalcombinationofarrays:np.concatenate((arr1,arr2),axis=0)[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints475.Arraydatatypes(4)transformingtheformofthearrayCuttingarraysSplitthearrayhorizontallyusingthehsplitfunction:np.hsplit(arr1,2)Splitanarrayverticallyusingthevsplitfunction:np.vsplit(arr,2)Splitthearrayhorizontallyusingthesplitfunction:np.split(arr,2,axis=1)Usethesplitfunctiontosplitanarrayvertically:np.split(arr,2,axis=0)[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints486.NumPy-Broadcast

Broadcastisawayfornumpytoperformnumericalcalculationonarraysofdifferentshapes.Arithmeticoperationsonarraysareusuallyperformedoncorrespondingelements.[Example7-6]a*bNote:Thenumberofdimensionsisthesame,andthelengthofeachdimensionisthesame.12345importnumpyasnpa=np.array([1,2,3,4])b=np.array([10,20,30,40])X=a*bprint(X)[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints497.Numpy-operationbetweenarrayandscalarvalueArraysareimportantbecausetheyallowyoutoperformbulkoperationsondatawithoutwritingloopsAnyarithmeticoperationbetweenarraysofequalsizeappliestheoperationtotheelementlevel.[Example]a*b[Example]a-b12345importnumpyasnpa=np.array([1,2,3,4])b=np.array([10,20,30,40])X=a-bprint(X)[Example]1/b[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints508.NumPy-BasicIndexSupposethateachnamecorrespondstoarowinthedataarray,andwewanttoselectallrowscorrespondingtothename"Bob"12345importnumpyasnpnames=np.array(['Bob','Joe','Will','Bob','Joe’])data

=

np.random.randn(5,4) #Generatenormallydistributedrandomdataprint(names==‘Bob’)print(data[names=='Bob’])Thelengthofthebooleanarraymustbethesameasthelengthoftheaxisbeingindexed(here5)Booleanindexes[numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints518.NumPy-BasicIndexFancyindexing12345importnumpyasnparr=np.empty((5,4)) #Createa5*4arraywithoutanyspecificvaluesforiinrange(5):arr[i]=iprint(arr)[[0.0.0.0.][1.1.1.1.][2.2.2.2.][3.3.3.3.][4.4.4.4.]][numpyinstallationandcommonfunctions]Knowledgepoint12Knowledgepoints528.NumPy-BasicIndexaccessingthearraybyindexIn[29]:arr=np.arange(10)Print('Indexingresult:',arr[5])#UseintegerassubscripttogetanelementinthearrayOut[29]:Theind

温馨提示

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

评论

0/150

提交评论