### 世界杯：用Python分析熱門奪冠球隊-(附源代碼)

2018年，火熱的世界杯即將拉開序幕。在比賽開始之前，我們不妨用 Python 來對參賽隊伍的實力情況進行分析，並大膽的預測下本屆世界杯的奪冠熱門球隊。

• 找出哪些隊伍是首次進入世界杯的黑馬隊伍
• 找出2018年32強中之前已經進入過世界杯，但在世界杯上沒有贏得過一場比賽的隊伍

• window 7 系統
• python 3.6
• Jupyter Notebook
• pandas version 0.22.0

``````import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline
plt.style.use('ggplot')

df = pd.read_csv('results.csv')
df.head()
``````

• 日期
• 主隊名稱
• 客隊名稱
• 主隊進球數 （不含點球）
• 客隊進球數 （不含點球）
• 比賽的類型
• 比賽所在城市
• 比賽所在國家
• 是否中立

## 1、 獲取所有世界杯比賽的數據（不含預選賽）

``````df_FIFA_all = df[df['tournament'].str.contains('FIFA', regex=True)]
df_FIFA = df_FIFA_all[df_FIFA_all['tournament']=='FIFA World Cup']
df_FIFA.head()
``````

``````df_FIFA.loc[:,'date'] = pd.to_datetime(df_FIFA.loc[:,'date'])
df_FIFA['year'] = df_FIFA['date'].dt.year
df_FIFA['diff_score'] = df_FIFA['home_score']-df_FIFA['away_score']
df_FIFA['win_team'] = ''
df_FIFA['diff_score'] = pd.to_numeric(df_FIFA['diff_score'])
``````

``````# The first method to get the winners

df_FIFA.loc[df_FIFA['diff_score']> 0, 'win_team'] = df_FIFA.loc[df_FIFA['diff_score']> 0, 'home_team']
df_FIFA.loc[df_FIFA['diff_score']< 0, 'win_team'] = df_FIFA.loc[df_FIFA['diff_score']< 0, 'away_team']
df_FIFA.loc[df_FIFA['diff_score']== 0, 'win_team'] = 'Draw'

df_FIFA.head()

# The second method to get the winners

def find_win_team(df):
winners = []
for i, row in df.iterrows():
if row['home_score'] > row['away_score']:
winners.append(row['home_team'])
elif row['home_score'] < row['away_score']:
winners.append(row['away_team'])
else:
winners.append('Draw')
return winners

df_FIFA['winner'] = find_win_team(df_FIFA)
df_FIFA.head()
``````

## 2、 獲取世界杯所有比賽的前20強數據情況

### 2.1 獲取世界杯所有比賽獲勝場數最多的前20強數據

``````s = df_FIFA.groupby('win_team')['win_team'].count()
s.sort_values(ascending=False, inplace=True)
s.drop(labels=['Draw'], inplace=True)
``````

``````s.head(20).plot(kind='bar', figsize=(10,6), title='Top 20 Winners of World Cup')
``````

``````s.sort_values(ascending=True,inplace=True)
s.tail(20).plot(kind='barh', figsize=(10,6), title='Top 20 Winners of World Cup')
``````

``````s_percentage = s/s.sum()
s_percentage
s_percentage.tail(20).plot(kind='pie', figsize=(10,10), autopct='%.1f%%',
startangle=173, title='Top 20 Winners of World Cup', label='')
``````

``````s.get('China', default = 'NA')
s.get('Japan', default = 'NA')
s.get('Korea DPR', default = 'NA')
s.get('Korea Republic', default = 'NA')
s.get('Egypt', default = 'NA')
``````

### 2.2 各個國家隊進球總數量情況

``````df_score_home = df_FIFA[['home_team', 'home_score']]
column_update = ['team', 'score']
df_score_home.columns = column_update
df_score_away = df_FIFA[['away_team', 'away_score']]
df_score_away.columns = column_update
df_score = pd.concat([df_score_home,df_score_away], ignore_index=True)
s_score = df_score.groupby('team')['score'].sum()
s_score.sort_values(ascending=False, inplace=True)
s_score.sort_values(ascending=True, inplace=True)
s_score.tail(20).plot(kind='barh', figsize=(10,6), title='Top 20 in Total Scores of World Cup')
``````

## 3、2018年世界杯32強分析

2018年世界杯的分組情況如下：

``````team_list = ['Russia', 'Germany', 'Brazil', 'Portugal', 'Argentina', 'Belgium', 'Poland', 'France',
'Spain', 'Peru', 'Switzerland', 'England', 'Colombia', 'Mexico', 'Uruguay', 'Croatia',
'Denmark', 'Iceland', 'Costa Rica', 'Sweden', 'Tunisia', 'Egypt', 'Senegal', 'Iran',
'Serbia', 'Nigeria', 'Australia', 'Japan', 'Morocco', 'Panama', 'Korea Republic', 'Saudi Arabia']
for item in team_list:
if item not in s_score.index:
print(item)

out:
Iceland
Panama
``````

``````df_top32 = df_FIFA[(df_FIFA['home_team'].isin(team_list))&(df_FIFA['away_team'].isin(team_list))]
``````

### 3.1 自1872年以來，32強數據情況

``````s_32 = df_top32.groupby('win_team')['win_team'].count()
s_32.sort_values(ascending=False, inplace=True)
s_32.drop(labels=['Draw'], inplace=True)
s_32.sort_values(ascending=True,inplace=True)
s_32.plot(kind='barh', figsize=(8,12), title='Top 32 of World Cup since year 1872')
``````

``````df_score_home_32 = df_top32[['home_team', 'home_score']]
column_update = ['team', 'score']
df_score_home_32.columns = column_update
df_score_away_32 = df_top32[['away_team', 'away_score']]
df_score_away_32.columns = column_update
df_score_32 = pd.concat([df_score_home_32,df_score_away_32], ignore_index=True)
s_score_32 = df_score_32.groupby('team')['score'].sum()
s_score_32.sort_values(ascending=False, inplace=True)
s_score_32.sort_values(ascending=True, inplace=True)
s_score_32.plot(kind='barh', figsize=(8,12), title='Top 32 in Total Scores of World Cup since year 1872')
``````

## 4、綜合結論

2018年世界杯的32支隊伍，根據以往的世界杯比賽數據來看，預測前三強為 德國、阿根廷和巴西，其中德國隊應該是奪冠的最大熱門。

#### 注意！

© 2014-2021 ITdaan.com