《python數(shù)據(jù)分析與應(yīng)用》 課件 史浩 第8、9章 Python數(shù)據(jù)可視化、核心數(shù)據(jù)處理庫pandas_第1頁
《python數(shù)據(jù)分析與應(yīng)用》 課件 史浩 第8、9章 Python數(shù)據(jù)可視化、核心數(shù)據(jù)處理庫pandas_第2頁
《python數(shù)據(jù)分析與應(yīng)用》 課件 史浩 第8、9章 Python數(shù)據(jù)可視化、核心數(shù)據(jù)處理庫pandas_第3頁
《python數(shù)據(jù)分析與應(yīng)用》 課件 史浩 第8、9章 Python數(shù)據(jù)可視化、核心數(shù)據(jù)處理庫pandas_第4頁
《python數(shù)據(jù)分析與應(yīng)用》 課件 史浩 第8、9章 Python數(shù)據(jù)可視化、核心數(shù)據(jù)處理庫pandas_第5頁
已閱讀5頁,還剩36頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

第8章Python數(shù)據(jù)可視化Python數(shù)據(jù)分析與應(yīng)用1CONTENTS8.1知識準(zhǔn)備8.2代碼補全和知識拓展8.3實訓(xùn)任務(wù):視頻網(wǎng)站數(shù)據(jù)可視化8.4延伸高級任務(wù)目錄8.5課后習(xí)題2知識準(zhǔn)備132.Matplotlib圖形的詳細(xì)設(shè)置Matplotlib名稱可以被分解為:Math(數(shù)學(xué))+plot(圖表圖形)+lib(庫),因此將其合在一起稱之為數(shù)學(xué)圖表庫。Matplotlib是Python編程語言最常用的繪圖工具包,同時作為Python數(shù)據(jù)分析三劍客之一,是最基礎(chǔ)的Python可視化庫。8.1.2Python可視化庫知識準(zhǔn)備importmatplotlib.pyplotaspltimportpandasaspddf=pd.read_excel('./東三省GDP.xlsx’)x=df['年份']#設(shè)定X變量數(shù)據(jù)y=df['吉林省GDP增長率']#設(shè)定Y變量數(shù)據(jù)plt.plot(x,y)#繪制折線圖plt.show()#顯示圖形#設(shè)置畫布大小為1200*600,背景色為黃色plt.figure(figsize=(12,6),facecolor='y')#添加網(wǎng)格plt.grid()#解決中文無法顯示的問題plt.rcParams['font.sans-serif']=['SimHei']#繪制折線圖,并設(shè)置顏色、線條樣式、標(biāo)記樣式plt.plot(x,y,color='r',linestyle='--',marker='o',mfc='w')#添加數(shù)據(jù)標(biāo)簽fora,binzip(x,y):plt.text(a,b+0.5,'%.2f'%b,ha='center',va='bottom',fontsize=8)#設(shè)置X軸數(shù)據(jù)plt.xticks(x)#添加圖表標(biāo)題plt.title('吉林省GDP增長率')#添加圖例plt.legend(('GDP增長率',))48.1.1可視化的作用8.1.3Matplotlib和Seaborn庫的安裝8.1.4Matplotlib1.快速繪制Matplotlib圖形代碼補全和知識拓展25frompylabimport*X=np.linspace(__________________________)C,S=np.cos(X),np.sin(X)plot(X,C)plot(X,S)show()請補充代碼繪制出函數(shù)圖形。8.2.1代碼補全:1.繪制sin和cos函數(shù)圖像6importnumpyasnp(__________________________)fig=plt.figure()fig.subplots_adjust(top=0.8)ax1=fig.add_subplot(__________________________)ax1.set_ylabel(__________________________)ax1.set_title('Asinewave')t=np.arange(0.0,1.0,0.01)s=np.sin(2*np.pi*t)line,=ax1.plot(t,s,color='blue',(__________________________))#Fixingrandomstateforreproducibilitynp.random.seed(19680801)ax2=fig.add_axes([0.15,0.1,0.7,0.3])n,bins,patches=ax2.hist(np.random.randn(1000),50,facecolor='yellow',edgecolor='yellow')(__________________________)plt.show()請補充代碼繪制出函數(shù)圖形。8.2.1代碼補全:2.完成圖形7可以使用比較簡單的代碼快速繪制出內(nèi)容比較完整的統(tǒng)計圖形1.Seaborn繪圖importseabornassnsimportmatplotlib.pyplotasplta=[1,2,3,4,5]b=[5,10,15,20,25]sns.barplot(x=a,y=b)#用seaborn繪制條形圖plt.show()2.Seaborn作圖的基本操作8.2.2知識拓展:Seaborn實訓(xùn)任務(wù):視頻網(wǎng)站數(shù)據(jù)可視化39#1.讀取數(shù)據(jù)gb_data=np.loadtxt("GB_video_data_numbers.csv",delimiter=",")print(gb_data)#2.獲取評論數(shù)gb_data_com=gb_data[:,3]print(gb_data_com)#極差gb_ptp=max(gb_data_com)-min(gb_data_com)print(gb_ptp)#582505.0#組距->>根據(jù)極差考慮需要多少組來確定大概組距d=25000#組數(shù)->>極差/組距bins_nums_gb=int(gb_ptp/d)print(bins_nums_gb)#直方圖plt.hist(gb_data_com,bins=bins_nums_gb)#圖形展示plt.show()使用Matplotlib繪制英國與美國Youtube數(shù)據(jù)各自評論數(shù)量的圖形,查看其評論數(shù)主要分布在哪個區(qū)間數(shù)據(jù)文件名稱分別為:GB_video_data_numbers.csv(英國)與US_video_data_numbers.csv(美國)8.3實訓(xùn)任務(wù):英國與美國Youtube數(shù)據(jù)可視化10#評論在100000后的數(shù)目很少,無參考價值,進行簡單數(shù)據(jù)清洗->>刪除#清洗過后的數(shù)據(jù)gb_data_com_useful=[]foriingb_data_com:ifi<100000:gb_data_com_useful.append(i)#重新計算極差、組距,組數(shù)#極差gb_ptp=max(gb_data_com_useful)-min(gb_data_com_useful)#gb_ptp->>83992.0#組距d=3000#組數(shù)bins_gb=int(gb_ptp/d)print(bins_gb)#可視化plt.hist(gb_data_com_useful,bins=bins_gb)#設(shè)置顯示中文字體plt.rcParams["font.sans-serif"]=["SimHei"]#圖形展示plt.show()8.3實訓(xùn)任務(wù):英國與美國Youtube數(shù)據(jù)可視化11由于之前的圖形無法清晰判斷數(shù)據(jù)分布的主要區(qū)間,數(shù)據(jù)內(nèi)容展示的不夠清晰。因此需要再次對數(shù)據(jù)進行清洗,對有參考價值的數(shù)據(jù)繼續(xù)進行分析,代碼如下所示。#經(jīng)過兩次清洗,圖還是不清晰,再次進行清洗,10000之后數(shù)據(jù)無參靠價值#清洗過后的數(shù)據(jù)gb_data_com_useful=[]foriingb_data_com:(__________________________)(__________________________)#重新計算極差、組距,組數(shù)#極差gb_ptp=max(gb_data_com_useful)-min(gb_data_com_useful)#gb_ptp->>9933.0#組距d=500#組數(shù)bins_gb=int(gb_ptp/d)print(bins_gb)#可視化plt.hist(gb_data_com_useful,bins=bins_gb,density=True)#對x軸進行更精細(xì)劃分x_ticks=[iforiinrange(0,10500,500)]#可添加合適標(biāo)簽x_label=[f"{i}次"foriinrange(0,10500,500)]plt.xticks(x_ticks,x_label,rotation=45)#添加組件plt.xlabel("次數(shù)")plt.ylabel("頻率")plt.title("GB評論次數(shù)分布圖")8.3實訓(xùn)任務(wù):英國與美國Youtube數(shù)據(jù)可視化12然而上述代碼獲得的顯示效果仍然不夠理想,請繼續(xù)編寫程序進行可視化展示與分析。最終我們會得到數(shù)據(jù)可視化之后一張較為滿意直方圖延伸高級任務(wù)413importmatplotlib.datesasmdatesimportmatplotlib.cbookascbookyears=mdates.YearLocator()#everyyearmonths=mdates.MonthLocator()#everymonthyearsFmt=mdates.DateFormatter('%Y')withcbook.get_sample_data(os.getcwd()+'/sample_data/goog.npz',asfileobj=True,np_load=True)asdatafile:r=datafile['price_data'].view(np.recarray)print()fig,ax=plt.subplots()ax.plot(r.date,r.adj_close)#formattheticksax.xaxis.set_major_locator(years)ax.xaxis.set_major_formatter(yearsFmt)ax.xaxis.set_minor_locator(months)8.4延伸高級任務(wù):繪制股票走勢圖148.4.1讀入npz文件進行繪制datemin=datetime.date(np.datetime64(r.date.min()).astype(object).year,1,1)datemax=datetime.date(np.datetime64(r.date.max()).astype(object).year+1,1,1)ax.set_xlim(datemin,datemax)#formatthecoordsmessageboxdefprice(x):return'$%1.2f'%xax.format_xdata=mdates.DateFormatter('%Y-%m-%d')ax.format_ydata=priceax.grid(True)#rotatesandrightalignsthexlabels,andmovesthebottomofthe#axesuptomakeroomforthemfig.autofmt_xdate()8.4延伸高級任務(wù):繪制股票走勢圖158.4.1讀入npz文件進行繪制#讀取AAPL.csv文件,并繪制AAPL股票走勢圖importosfromdatetimeimportdatetimeimportnumpyasnpimportmatplotlib.pyplotaspltimportmatplotlib.cbookascbookwithcbook.get_sample_data(os.getcwd()+'/sample_data/AAPL.csv',asfileobj=True,np_load=True)asdatafile:f=datafiletitle=f.readline().strip().split(",")print(title)data=np.loadtxt(f,dtype={'names':('Date','Open','High','Low','Close','AdjClose','Volume'),'formats':('S10','<f8','<f8','<f8','<f8','<f8','i')},delimiter=",")#i=integer,<f8=0.256,f8=0.25600001298浮點類型,#S10="MM-DD-YYYY"字符串類型,長度為10

8.4延伸高級任務(wù):繪制股票走勢圖168.4.2讀入csv文件進行繪制

#轉(zhuǎn)為列表格式

lists2=[]forrowinrange(len(data)):txt=data[row]tmp=[]forcolinrange(len(txt)):s1=str(txt[col]).strip('b').strip("'")ifcol==0:d1=datetime.strptime(s1,"%Y-%m-%d")tmp.append(d1)else:tmp.append(float(s1))lists2.append(tmp)

#列表轉(zhuǎn)為numpy格式

a=np.array(lists2)

#繪制圖形

plt.plot(a[:,0],a[:,5])plt.show()8.4延伸高級任務(wù):繪制股票走勢圖178.4.2讀入csv文件進行繪制課后習(xí)題518課后習(xí)題習(xí)題11.分別用Matplotlib和Seaborn繪制我國國民生產(chǎn)總值一、二、三產(chǎn)業(yè)十年增加值的折線圖(使用“國民生產(chǎn)總值構(gòu)成.xls”文件)。習(xí)題22.承接上題,繪制國民生產(chǎn)總值一、二、三產(chǎn)業(yè)十年增加值的面積圖。在同一圖形繪制十年國民生產(chǎn)總值柱形圖和十年國民生產(chǎn)總值增長率的折線圖。習(xí)題33.請讀入阿里巴巴的股票交易數(shù)據(jù),編寫程序按照左圖繪制出三張圖形。課后習(xí)題19謝謝觀賞20第9章核心數(shù)據(jù)處理庫pandasPython數(shù)據(jù)分析與應(yīng)用21CONTENTS9.1知識準(zhǔn)備9.2代碼補全和知識拓展9.3實訓(xùn)任務(wù)9.4延伸高級任務(wù)目錄9.5課后習(xí)題22知識準(zhǔn)備1239.1.3DataFrame對象df=pd.read_excel('data.xlsx’)df.to_excel('data.xlsx',index=False) 導(dǎo)出Excel文件知識準(zhǔn)備data={'Name':['John','Emma','Mike'],'Age':[25,28,32],'City':['NewYork','SanFrancisco','Chicago']}df=pd.DataFrame(data)print(df)運行結(jié)果:

NameAgeCity0John25NewYork1Emma28SanFrancisco2Mike32Chicago24 讀取Exccel文件9.1.1pandas庫簡介9.1.2Series對象字典和Series的相似之處importpandasaspd#定義學(xué)生成績數(shù)據(jù)name=['小明','小紅','小剛','小華','小李']score=[92,85,78,88,95]#創(chuàng)建Series對象s=pd.Series(score,index=name)知識準(zhǔn)備importpandasaspdimportnumpyasnparr=np.array([[1,2,3],[4,5,6],[7,8,9]])df=pd.DataFrame(arr,columns=['A','B','C'])print(df)運行結(jié)果:

ABC01231456278925從NumPy數(shù)組創(chuàng)建DataFramedf=pd.DataFrame(data)print(df[['總價','數(shù)量']])數(shù)據(jù)多列提取訪問一行數(shù)據(jù):.loc[index的值]訪問連續(xù)的某幾行數(shù)據(jù):.loc[起點index的值:結(jié)束index的值]#使用loc按照標(biāo)簽索引訪問連續(xù)行數(shù)據(jù)rows=data.loc[1:3]#使用.loc訪問不連續(xù)的某幾行數(shù)據(jù)selected_rows=data.loc[[1,3]]布爾索引和判斷條件#判斷條件:篩選年齡大于等于35的行condition=df['Age']>=35#多個判斷條件:篩選年齡大于30并且城市為'Paris'的行condition=(df['Age']>30)&(df['City']=='Paris')#應(yīng)用布爾索引,保留滿足條件的行filtered_df=df[condition]df=pd.DataFrame(data)#檢測缺失值print(df.isnull())缺失值的檢測df=pd.DataFrame(data)#使用指定值填充缺失值filled_df=df.fillna(value={'A':0,'B':'missing','C':'unknown'})#使用前一行的值填充缺失值filled_df=df.fillna(method='ffill’)#使用后一行的值填充缺失值filled_df=df.fillna(method='bfill')填充缺失值df.drop(1,axis=0,inplace=True)df.drop('B',axis=1,inplace=True)刪除DataFrame中的行/列知識準(zhǔn)備df=pd.DataFrame({'A':[1,np.nan,3],'B':[np.nan,5,6]})df.dropna(axis=0,how='any',inplace=True)刪除DataFrame中包含任何缺失值的行刪除DataFrame中整行都是缺失值的行df=pd.DataFrame({'A':[np.nan,np.nan,np.nan],'B':[4,np.nan,6]})df.dropna(axis=0,how='all',inplace=True)df=pd.DataFrame({'A':[1,2,2,3,4,4],'B':['a','b','b','c','d','d']})df_dropped=df.drop_duplicates()刪除重復(fù)值代碼補全和知識拓展227importpandasaspd#讀取路徑為"/視頻會員訂單數(shù)據(jù)源.csv"的文件,賦值給變量dfdf=(__________)#商品價格price,單位分轉(zhuǎn)化成元df['price']=df['price']/100#使用to_datetime()函數(shù),將訂單創(chuàng)建時間create_time和支付時間pay_time,轉(zhuǎn)化成時間格式df['create_time']=(__________)df['pay_time']=(__________)#使用布爾索引和isnull函數(shù),將payment_provider這一列的缺失值篩選出,賦值給變量dfPayNull#dfPayNull就是,包含所有payment_provider這一列缺失值的行dfPayNull=(__________)#TODO使用drop函數(shù),將dfPayNull,也就是包含所有payment_provider這一列缺失值的行刪除df.drop(__________)#使用(),快速瀏覽數(shù)據(jù)集()對數(shù)據(jù)的質(zhì)量進行檢查和處理。9.2.1代碼補全:1.會員信息處理28#導(dǎo)入pandas模塊,簡稱pdimportpandasaspd#定義一個字典datadata={'name':['May','Tony','Kevin'],'score':[689,659,635]}#定義一個列表rank,內(nèi)含參數(shù)1,2,3,rank=(_____________)#使用pd.DataFrame()函數(shù),傳入?yún)?shù):字典data作為value和columns,列表rank作為index#構(gòu)造出的DataFrame賦值給performanceperformance=(_____________)#輸出performance這個DataFrameprint(performance)使用DataFrame構(gòu)造函數(shù),將定義的字典data和列表rank作為參數(shù)傳入,生成一個DataFrame,并賦值給變量performance。9.2.1代碼補全:4.班級成績表創(chuàng)建29importpandasaspd#創(chuàng)建一個Series對象math_scores=pd.Series([85,90,76,92,88,95,84,79,91,87],index=['Tom','Jerry','Alice','Bob','Linda','John','Emily','David','Amy','Sophia'])#提取前五名學(xué)生的成績(______________)#打印切片結(jié)果(______________)對假設(shè)有一位班主任想要分析學(xué)生的成績情況。請使用pandas創(chuàng)建一個Series對象,記錄一班學(xué)生的數(shù)學(xué)成績,并根據(jù)索引進行切片操作,提取前五名學(xué)生的成績。。9.2.1代碼補全:5.學(xué)生成績切片操作30在pandas中,mean()是一個用于計算數(shù)據(jù)集均值的方法。它用于計算DataFrame中的列的平均值。round()是一個用于對數(shù)據(jù)進行四舍五入的方法。一些計算方法#定義一個嵌套列表data,內(nèi)含參數(shù)May,689;Tony,659;Kevin,635。data=(_____________)#定義一個列表rankrank=[1,2,3]#使用pd.DataFrame()函數(shù),嵌套列表data和列表rank作為參數(shù)傳入,并且使用參數(shù)columns自定義列索引columns:#構(gòu)造出的DataFrame賦值給resultresult=(_____________)用列表構(gòu)造DataFrame9.2.2知識拓展:正則表達(dá)式9.3實訓(xùn)任務(wù)332請完成以下任務(wù):1.創(chuàng)建一個DataFrame,并將原始數(shù)據(jù)導(dǎo)入。2.檢查數(shù)據(jù)中是否存在缺失值,并處理這些缺失值。3.將銷售日期列的數(shù)據(jù)類型轉(zhuǎn)換為日期類型,并將其設(shè)置為DataFrame的索引。4.去除重復(fù)的記錄。5.計算每個訂單的銷售總金額,并添加為新的一列。6.根據(jù)產(chǎn)品名稱分組,并計算每種產(chǎn)品的銷售數(shù)量總和和銷售金額總和。7.根據(jù)銷售日期按月份進行分組,并計算每月的銷售數(shù)量總和和銷售金額總和。8.將清洗和處理后的數(shù)據(jù)保存為一個新的CSV文件。9.3.1銷售數(shù)據(jù)處理9.3實訓(xùn)任務(wù)33創(chuàng)建一個Series[1,2,3,4,5,6,7,8,9,10],判斷Series中的元素是否全部大于5?importpandasaspds1=pd.Series([1,2,3,4,5,6,7,8,9,10])print(s1)#顯示兩列,第一列為索引,第二列為值print(s1[4])#打印索引4對應(yīng)的值:5allabove5=Trueforindexinrange(0,len(s1)):ifs1[index]<=5:allabove5=Falseifallabove5:print('TheSe

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論