首頁 > 綜合 > 正文

環(huán)球快資訊:歷屆奧運(yùn)會獎(jiǎng)牌排行榜排名 數(shù)據(jù)整理分享

2023-02-28 15:14:10來源:互聯(lián)網(wǎng)  

摘 要在制作動態(tài)排序動畫之前,我們看一下數(shù)據(jù)的整理情況:

a、對第1)種大部分?jǐn)?shù)據(jù)的情況,先爬取下來,輸出到excel(1);

b、對第2)種小部分?jǐn)?shù)據(jù)的情況,也先爬取下來,輸出到另一個(gè)excel(2);


【資料圖】

c、對第3)種個(gè)別的,還有第31-32屆的數(shù)據(jù),算了,別折騰了,手動復(fù)制粘貼到excel(3)吧。

d、最后把這3個(gè)excel合并到一個(gè)excel,進(jìn)行數(shù)據(jù)處理吧。

二、數(shù)據(jù)處理經(jīng)過1896-2021歷屆奧運(yùn)會獎(jiǎng)牌榜動態(tài)排序系列的數(shù)據(jù)處理(第二篇),我們得到了a數(shù)據(jù):

看到這張數(shù)據(jù)表,還有以下幾點(diǎn)需要調(diào)整:

1、合并3個(gè)excel數(shù)據(jù);

2、標(biāo)題、年份列順序調(diào)整到名次前;

3、'國家'列名修改為'國家/地區(qū)';

4、計(jì)算獎(jiǎng)牌的合計(jì)數(shù)量;

5、根據(jù)年份,計(jì)算各國的獎(jiǎng)牌合計(jì)數(shù)排名。

1)合并DataFrame:concat(),合并函數(shù)還有merge、join函數(shù),有興趣可以進(jìn)入以下鏈接進(jìn)行學(xué)習(xí)()

df1 = pd.read_excel("./data/Olympic10.xlsx")df2 = pd.read_excel("./data/Olympic11.xlsx")df3 = pd.read_excel("./data/Olympic12.xlsx")df = pd.concat([df1,df2,df3],axis=0,ignore_index=True,sort=True)2)調(diào)賬列順序

columns = ['標(biāo)題','年份','國家','金牌','銀牌','銅牌']df = pd.DataFrame(df, columns=columns)3)列名修改

df.rename(columns={'國家':'國家/地區(qū)'},inplace=True)4)計(jì)算獎(jiǎng)牌合計(jì)

df['合計(jì)'] = ''df['合計(jì)'] = df['金牌'] + df['銀牌'] + df['銅牌']5)按年份,計(jì)算各國的獎(jiǎng)牌合計(jì)數(shù)排名

df['排名'] = df.groupby('年份',axis=0)['合計(jì)'].rank(method='first',ascending=False)另外,再對數(shù)據(jù)進(jìn)行一些微調(diào)

df=df.drop_duplicates(subset=['年份', '國家/地區(qū)'], keep='first')df.sort_values(["年份","排名"],inplace=True,ascending=True)#將國家/地區(qū)列字符串中的空格都去除df['國家/地區(qū)'].replace('\s+','',regex=True,inplace=True) 最終獲得我們的完整數(shù)據(jù)

df.to_excel("./data/Olympic_final.xlsx")完整代碼如下:

import pandas as pddf1 = pd.read_excel("./data/Olympic10.xlsx")df2 = pd.read_excel("./data/Olympic11.xlsx")df3 = pd.read_excel("./data/Olympic12.xlsx")df = pd.concat([df1,df2,df3],axis=0,ignore_index=True,sort=True)columns = ['標(biāo)題','年份','國家','金牌','銀牌','銅牌']df = pd.DataFrame(df, columns=columns)df.rename(columns={'國家':'國家/地區(qū)'},inplace=True)df['合計(jì)'] = ''df['合計(jì)'] = df['金牌'] + df['銀牌'] + df['銅牌']df.loc[df['年份']==1894,'年份'] = 1900df=df.drop_duplicates(subset=['年份', '國家/地區(qū)'], keep='first')df['排名'] = df.groupby('年份',axis=0)['合計(jì)'].rank(method='first',ascending=False)df.sort_values(["年份","排名"],inplace=True,ascending=True)#將國家/地區(qū)列字符串中的空格都去除df['國家/地區(qū)'].replace('\s+','',regex=True,inplace=True) df.to_excel("./data/Olympic_final.xlsx")輸出結(jié)果:

三、動態(tài)排序經(jīng)過一系列的數(shù)據(jù)處理,終于可以驗(yàn)證下勞動成果了。完整代碼如下:

import pandas as pdimport randomimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport matplotlib.animation as animationfrom IPython.display import HTMLimport matplotlibplt.rcParams['font.sans-serif']=['SimHei'] #顯示中文標(biāo)簽plt.rcParams['axes.unicode_minus']=False #這兩行需要手動設(shè)置#防止動漫內(nèi)存太大,報(bào)錯(cuò)matplotlib.rcParams['animation.embed_limit'] = 2**128def randomcolor(): colorlist = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] color ='' for i in range(6): color += random.choice(colorlist) return '#'+ colordf = pd.read_excel(./data/Olympic_final.xlsx")#對地區(qū)列表進(jìn)行去重,分類;area_list1 = set(df['國家/地區(qū)'])# color_list用于存放隨機(jī)生成顏色代碼個(gè)數(shù)# 因?yàn)楹竺鎱^(qū)域個(gè)數(shù) 要與顏色個(gè)數(shù)保持一致,這里用了len函數(shù);color_list =[]for i in range(len(area_list1)): str_1 = randomcolor() color_list.append(str_1) str_1 = randomcolor() #area_list轉(zhuǎn)化為列表area_list_1 = [i for i in area_list1]#colors表示 所在城市:顏色 一一對應(yīng)字典形式;colors =dict(zip(area_list_1,color_list))# 用plt加理圖表,figsize表示圖標(biāo)長寬,ax表示標(biāo)簽fig, ax = plt.subplots(figsize=(15, 8))#dras_barchart生成current_year這一年各城市人口基本情況;def draw_barchart(current_year): #dff對year==current_year的行,以”合計(jì)“降序排序,取前十名; dff = df[df['年份'].eq(current_year)].sort_values(by='合計(jì)',ascending = True).tail(10) # 所有坐標(biāo)、標(biāo)簽清除 ax.clear() #顯示顏色、城市名字 ax.barh(dff['國家/地區(qū)'],dff['合計(jì)'],color = [colors[x] for x in dff['國家/地區(qū)']]) dx = dff['合計(jì)'].max()/200 #ax.text(x,y,name,font,va,ha) # x,y表示位置; # name表示顯示文本; # va,ba分別表示水平位置,垂直放置位置; for i ,(value,name) in enumerate(zip(dff['合計(jì)'], dff['國家/地區(qū)'])): ax.text(value-dx,i,name,size=18,weight=600,ha ='right',va = 'bottom',color='#777777') ax.text(value+dx,i ,f'{value:,.0f}',size = 14,ha = 'left',va ='center') #ax.transAxes表示軸坐標(biāo)系,(1,0.4)表示放置位置 ax.text(1,0.4,current_year,transform = ax.transAxes,color ='#777777',size = 46,ha ='right',weight=800) ax.text(0,1.06,'Olympic Medals',transform = ax.transAxes,size=12,color='#777777') #set_major_formatter表示刻度尺格式; ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) ax.xaxis.set_ticks_position('top') ax.tick_params(axis='x',colors='#777777',labelsize=12) ax.set_yticks([]) #margins表示自動縮放余額; ax.margins(0,0.01) # 設(shè)置后面的網(wǎng)格 ax.grid(which='major',axis='x',linestyle='-') #刻度線和網(wǎng)格線是在圖標(biāo)上方還是下方,True為下方 ax.set_axisbelow(True) ax.text(0,1.15,'歷屆奧運(yùn)會獎(jiǎng)牌排行榜', transform=ax.transAxes,size=24,weight=600,ha='left',va='top') ax.text(1,0,'Officetouch制作',transform = ax.transAxes, size=16,color ='#777777',ha = 'right', bbox = dict(facecolor='white',alpha = 0.8,edgecolor='white')) #取消圖表周圍的方框顯示 plt.box(False)#draw_barchart(2008)#將原來的靜態(tài)圖拼接成動畫fig, ax = plt.subplots(figsize=(15, 8))animator = animation.FuncAnimation(fig, draw_barchart, frames=df['年份'].drop_duplicates(),interval = 1000)animator.save("./data/Olympic.gif", writer='pillow')輸出結(jié)果:

結(jié) 語學(xué)習(xí)需要耐心和時(shí)間的投入,初學(xué)的時(shí)候可能需要投入比較多的時(shí)間和精力,但只要有這樣一個(gè)過程,你就會脫胎換骨,一點(diǎn)一滴的積累成就自己。

1、數(shù)據(jù)采集-爬蟲;

1896-2021歷屆奧運(yùn)會獎(jiǎng)牌動態(tài)排序動畫(Python數(shù)據(jù)分析實(shí)戰(zhàn)1)

2、數(shù)據(jù)處理-數(shù)據(jù)清洗;

1896-2021歷屆奧運(yùn)會獎(jiǎng)牌榜(Python數(shù)據(jù)處理)

3、數(shù)據(jù)動態(tài)排序。(本篇文章)

因?yàn)閵W運(yùn)數(shù)據(jù)連續(xù)性較差,如果我們分析一些連續(xù)性強(qiáng)的數(shù)據(jù),如各國人口數(shù)據(jù),動態(tài)排序的效果會好很多。

標(biāo)簽:

相關(guān)閱讀

精彩推薦

相關(guān)詞

推薦閱讀