版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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語言程序設(shè)計(jì)6《綜合案例1》綜合案例1:電力招投標(biāo)數(shù)據(jù)讀取與處理7數(shù)據(jù)分析三部曲:(1)數(shù)據(jù)源讀取——通過編程完成對(duì)文件“1_投標(biāo)數(shù)據(jù)案例.xlsx”中不良行為信息數(shù)據(jù)的讀取;(2)數(shù)據(jù)篩選與合并——對(duì)讀取的數(shù)據(jù)進(jìn)行篩選與合并;(3)數(shù)據(jù)輸出——對(duì)上一步獲取的數(shù)據(jù)進(jìn)行輸出,形成新文件。案例背景:國網(wǎng)公司為了保證物資、設(shè)備、服務(wù)的優(yōu)良品質(zhì),對(duì)供應(yīng)商管理體系中有一個(gè)不良行為的處罰,對(duì)履約不好、有質(zhì)量問題等的供應(yīng)商,會(huì)納入不良行為處罰。一旦供應(yīng)商存在不良行為處罰,那么就不參與相應(yīng)的招投標(biāo)。8綜合案例1:電力招投標(biāo)數(shù)據(jù)讀取與處理1.源數(shù)據(jù)讀取讀取文件“1_投標(biāo)數(shù)據(jù)案例.xlsx”中的“案例1_供應(yīng)商投標(biāo)數(shù)據(jù)”和“案例1_不良行為數(shù)據(jù)”兩個(gè)工作表的數(shù)據(jù),分別記為table_a和table_b。代碼如下:12345678table_a_name="1_投標(biāo)數(shù)據(jù)案例"table_a_path=table_a_name+'.xlsx'sheet_a_name="案例1_供應(yīng)商投標(biāo)數(shù)據(jù)"table_a=pd.read_excel(table_a_path,sheet_name=sheet_a_name,converters={'供應(yīng)商代號(hào)':str}).dropna(axis=1,how='all')table_b_name="1_投標(biāo)數(shù)據(jù)案例"table_b_path=table_b_name+".xlsx"sheet_b_name="案例1_不良行為數(shù)據(jù)"table_b=pd.read_excel(table_b_path,sheet_name=sheet_b_name,converters={'供應(yīng)商代號(hào)':str})9綜合案例1:電力招投標(biāo)數(shù)據(jù)讀取與處理2.數(shù)據(jù)篩選與合并需要在投標(biāo)數(shù)據(jù)中篩選出不良行為的數(shù)據(jù),根據(jù)國網(wǎng)公司的處罰要求,如果不良行為數(shù)據(jù)中,處理范圍為“所有品類”,那么該供應(yīng)商所有投標(biāo)都不能參與,即在投標(biāo)數(shù)據(jù)中,需要剔除該供應(yīng)商的所有數(shù)據(jù);如果不良行為數(shù)據(jù)中,處理范圍為特定的品類,那么該供應(yīng)商不能參與特定品類的投標(biāo),即在投標(biāo)數(shù)據(jù)中,需要剔除特定該供應(yīng)商特定品類的投標(biāo)數(shù)據(jù)。1234567#處理所有品類的table_b_tmp=table_tmp[table_tmp['處理范圍']=='所有品類']table_c=table_a.merge(table_b_tmp,on=['供應(yīng)商代號(hào)'],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=['供應(yīng)商代號(hào)','包號(hào)','標(biāo)段名稱'],suffixes=('','_y'))table_specific=table_c[table_a.columns]10綜合案例1:電力招投標(biāo)數(shù)據(jù)讀取與處理3.數(shù)據(jù)輸出讀取第3步輸出的文件,輸出需剔除的數(shù)據(jù)和正常參與招投標(biāo)的數(shù)據(jù)。1234table_w=pd.concat([table_total,table_specific],axis=0)table_w.to_excel('不良行為投標(biāo)數(shù)據(jù).xlsx')table_y=table_a.drop(labels=table_w.index,axis=0)table_y.to_excel('正常投標(biāo)數(shù)據(jù).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語言程序設(shè)計(jì)16《綜合案例2》17綜合案例2:電力數(shù)據(jù)分析與可視化首先讀取需要的電力數(shù)據(jù),依據(jù)供應(yīng)商投標(biāo)報(bào)價(jià),針對(duì)異常數(shù)據(jù)進(jìn)行清洗,再通過透視表對(duì)電力報(bào)價(jià)最小值、最大值以及平均值統(tǒng)計(jì)分析,最后通過可視化展示數(shù)據(jù)。1.源數(shù)據(jù)讀取讀取文件“1_投標(biāo)數(shù)據(jù)案例.xlsx”中的“案例2_供應(yīng)商投標(biāo)報(bào)價(jià)工作表”數(shù)據(jù),賦值為p_data。代碼如下:1p_data=pd.read_excel(r'./1_投標(biāo)數(shù)據(jù)案例.xlsx',sheet_name='案例2_供應(yīng)商投標(biāo)報(bào)價(jià)')18綜合案例2:電力數(shù)據(jù)分析與可視化2.數(shù)據(jù)清洗為更好地對(duì)數(shù)據(jù)進(jìn)行分析,需要對(duì)源數(shù)據(jù)進(jìn)行清洗。針對(duì)本案例“供應(yīng)商投標(biāo)報(bào)價(jià)”數(shù)據(jù),使用3delta原則處理離群值,通過計(jì)算投標(biāo)價(jià)格的平均值u,標(biāo)準(zhǔn)差delta,以3delta原則來清洗無效數(shù)據(jù)。代碼如下:123456p_data['投標(biāo)價(jià)格(萬元)'].hist(bins=20)u=p_data['投標(biāo)價(jià)格(萬元)'].mean()#投標(biāo)價(jià)格的平均值delta=p_data['投標(biāo)價(jià)格(萬元)'].std()#投標(biāo)價(jià)格的標(biāo)準(zhǔn)差a=u-3*deltab=u+3*deltap_data=p_data[(p_data['投標(biāo)價(jià)格(萬元)']<=b)]19綜合案例2:電力數(shù)據(jù)分析與可視化3.數(shù)據(jù)透視表按照分標(biāo)名稱、包號(hào)進(jìn)行數(shù)量以及報(bào)價(jià)最小值、最大值以及平均值的統(tǒng)計(jì)分析,最后得出透視表。12345678#pt=pd.pivot_table(p_data,index=['分標(biāo)名稱','包號(hào)'],columns=[],values=['投標(biāo)價(jià)格(萬元)','分標(biāo)編號(hào)'],aggfunc={'投標(biāo)價(jià)格(萬元)':np.max,'投標(biāo)價(jià)格(萬元)':np.min,'投標(biāo)價(jià)格(萬元)':np.average,'分標(biāo)編號(hào)':'count'},margins=True)pt1=pd.pivot_table(p_data,index=['分標(biāo)名稱','包號(hào)'],columns=[],values=['投標(biāo)價(jià)格(萬元)','分標(biāo)編號(hào)'],aggfunc={'投標(biāo)價(jià)格(萬元)':np.max,'分標(biāo)編號(hào)':'count'},margins=False)pt2=pd.pivot_table(p_data,index=['分標(biāo)名稱','包號(hào)'],columns=[],values=['投標(biāo)價(jià)格(萬元)','分標(biāo)編號(hào)'],aggfunc={'投標(biāo)價(jià)格(萬元)':np.min,'分標(biāo)編號(hào)':'count'},margins=False)pt3=pd.pivot_table(p_data,index=['分標(biāo)名稱','包號(hào)'],columns=[],values=['投標(biāo)價(jià)格(萬元)','分標(biāo)編號(hào)'],aggfunc={'投標(biāo)價(jià)格(萬元)':np.average,'分標(biāo)編號(hào)':'count'},margins=False)pt1.to_excel(r'最大值.xlsx')pt2.to_excel(r'最小值.xlsx')pt3.to_excel(r'平均值.xlsx')print(pt1,pt2,pt3)20綜合案例2:電力數(shù)據(jù)分析與可視化4.數(shù)據(jù)可視化展示可視化代碼如下: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['投標(biāo)價(jià)格(萬元)']mean_price_district.plot(kind='bar')print(mean_price_district)plt.title(n)plt.xlabel(u"分標(biāo)名稱")plt.ylabel(u"投標(biāo)價(jià)格(萬元)")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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 物業(yè)供料施工方案
- 二零二五年度甲方代建代付農(nóng)村水利工程款合同
- 2025年度二零二五年度解除閑置廠房租賃合同及資產(chǎn)處置方案
- 2025購房合同解除通知書及房屋交接及維修協(xié)議
- 二零二五年度股東向公司提供無息借款的股權(quán)激勵(lì)合同
- 2025年度智能交通系統(tǒng)車位租賃與數(shù)據(jù)共享合同
- 二零二五年度托盤租賃與物流智能化升級(jí)合同
- 二零二五年度路基施工合同與施工現(xiàn)場(chǎng)臨時(shí)設(shè)施租賃
- 朝陽六上中考數(shù)學(xué)試卷
- 二零二五年度廢木材回收再制造承包合同4篇
- 中考模擬考試化學(xué)試卷與答案解析(共三套)
- 新人教版五年級(jí)小學(xué)數(shù)學(xué)全冊(cè)奧數(shù)(含答案)
- 風(fēng)電場(chǎng)升壓站培訓(xùn)課件
- 收納盒注塑模具設(shè)計(jì)(論文-任務(wù)書-開題報(bào)告-圖紙)
- 博弈論全套課件
- CONSORT2010流程圖(FlowDiagram)【模板】文檔
- 腦電信號(hào)處理與特征提取
- 高中數(shù)學(xué)知識(shí)點(diǎn)全總結(jié)(電子版)
- GB/T 10322.7-2004鐵礦石粒度分布的篩分測(cè)定
- 2023新譯林版新教材高中英語必修一重點(diǎn)詞組歸納總結(jié)
- 蘇教版四年級(jí)數(shù)學(xué)下冊(cè)第3單元第2課時(shí)“常見的數(shù)量關(guān)系”教案
評(píng)論
0/150
提交評(píng)論