-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculate_seasonal_stats.py
221 lines (187 loc) · 11.6 KB
/
calculate_seasonal_stats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import pandas as pd
def time_to_float(time_str):
if ':' in str(time_str):
minutes, seconds = time_str.split(':')
return float(minutes) + float(seconds) / 60
else:
return float(time_str)
def prepare_matches():
# Load the data
all_matches_stats = pd.read_csv("data/all_matches_stats.csv")
seasons = pd.read_csv("data/NBA_Seasons_Dates.csv")
# Converting columns to datetime
date_columns = ['Regular_season_start', 'Regular_season_end', 'Playin_start', 'Playin_end',
'Playoffs_start', 'Playoffs_end', 'Finals_start', 'Finals_end']
seasons[date_columns] = seasons[date_columns].apply(lambda x: pd.to_datetime(x, errors='coerce'))
all_matches_stats['GAME_DATE'] = pd.to_datetime(all_matches_stats['GAME_DATE'])
all_matches_stats['MIN'] = all_matches_stats['MIN'].apply(time_to_float)
# Drop unnecessary columns and add the season and match type columns
all_matches_stats.drop(columns=['NICKNAME', 'COMMENT', 'PLUS_MINUS', 'START_POSITION'], inplace=True)
all_matches_stats['SEASON'] = None
all_matches_stats['MATCH_TYPE'] = None
# Get the season for each match and what kind of match was it
for index, row in seasons.iterrows():
if row['Season'] == '1946-47':
all_matches_stats.loc[all_matches_stats['GAME_DATE'] <= row['Finals_end'], 'SEASON'] = row['Season']
else:
previous_final = seasons.loc[index - 1, 'Finals_end']
all_matches_stats.loc[(all_matches_stats['GAME_DATE'] > previous_final) & (all_matches_stats['GAME_DATE'] <= row['Finals_end']), 'SEASON'] = row['Season']
all_matches_stats.loc[(all_matches_stats['GAME_DATE'] >= row['Regular_season_start']) & (all_matches_stats['GAME_DATE'] <= row['Regular_season_end']), 'MATCH_TYPE'] = "Regular"
all_matches_stats.loc[(all_matches_stats['GAME_DATE'] >= row['Playoffs_start']) & (all_matches_stats['GAME_DATE'] <= row['Playoffs_end']), 'MATCH_TYPE'] = "Playoffs"
all_matches_stats.loc[(all_matches_stats['GAME_DATE'] >= row['Finals_start']) & (all_matches_stats['GAME_DATE'] <= row['Finals_end']), 'MATCH_TYPE'] = "Finals"
if not pd.isna(row['Playin_start']):
all_matches_stats.loc[(all_matches_stats['GAME_DATE'] >= row['Playin_start']) & (all_matches_stats['GAME_DATE'] <= row['Playin_end']), 'MATCH_TYPE'] = "Play-In"
# Add information about All-Star games
all_matches_stats.loc[(all_matches_stats['TEAM_CITY'] == 'East NBA All Stars') | (all_matches_stats['TEAM_CITY'] == 'West NBA All Stars'), 'MATCH_TYPE'] = "All-Star"
all_matches_stats.loc[(all_matches_stats['TEAM_ABBREVIATION'] == 'LBN') | (
all_matches_stats['TEAM_ABBREVIATION'] == 'STP') | (
all_matches_stats['TEAM_ABBREVIATION'] == 'GNS') | (
all_matches_stats['TEAM_ABBREVIATION'] == 'DRT'), 'MATCH_TYPE'] = "All-Star"
# Add information about final of the In-Season Tournament
all_matches_stats.loc[(all_matches_stats['GAME_ID'] == 62300001), 'MATCH_TYPE'] = "In-Season Tournament Final"
# Save the data
all_matches_stats.to_csv("data/matches_player_stats.csv", index=False)
def calculate_not_empty(row, column_to_check, column_to_return):
if pd.notna(row[column_to_check]):
return row[column_to_return]
else:
return None
def calculate_over_10(row):
num_of_stats_over_10 = 0
columns = ['PTS', 'REB', 'AST', 'STL', 'BLK']
for column in columns:
if row[column] >= 10:
num_of_stats_over_10 += 1
return num_of_stats_over_10
# Calculate the fantasy points for each player (based on NBA glossary)
def calculate_fantasy_points(row):
fantasy_points = 0
fantasy_points += row['PTS']
fantasy_points += row['REB'] * 1.2
fantasy_points += row['AST'] * 1.5
fantasy_points += row['STL'] * 3
fantasy_points += row['BLK'] * 3
fantasy_points += row['TO'] * -1
return fantasy_points
# Calculate the Player Impact Estimate (PIE) for each player (based on NBA glossary)
def calculate_pie(row):
pie = 0
pie += (row['PTS'] + row['FGM'] + row['FTM'] - row['FGA'] - row['FTA'] + row['DREB'] + 0.5 * row['OREB'] +
row['AST'] + row['STL'] + 0.5 * row['BLK'] - row['PF'] - row['TO'])
if (row['PTS_GAME'] + row['FGM_GAME'] + row['FTM_GAME'] - row['FGA_GAME'] - row['FTA_GAME'] +
row['DREB_GAME'] + 0.5 * row['OREB_GAME'] + row['AST_GAME'] + row['STL_GAME'] + 0.5 * row['BLK_GAME'] -
row['PF_GAME'] - row['TO_GAME']) == 0:
pie = 0
else:
pie /= (row['PTS_GAME'] + row['FGM_GAME'] + row['FTM_GAME'] - row['FGA_GAME'] - row['FTA_GAME'] +
row['DREB_GAME'] + 0.5 * row['OREB_GAME'] + row['AST_GAME'] + row['STL_GAME'] + 0.5 * row['BLK_GAME'] -
row['PF_GAME'] - row['TO_GAME'])
return pie
def calculate_seasonal_stats():
# Load the data
matches = pd.read_csv("data/matches_player_stats.csv")
team_results = pd.read_csv("data/matches_team_results.csv")
sum_columns = ['PTS', 'FGM', 'FTM', 'FGA', 'FTA', 'DREB', 'OREB', 'AST', 'STL', 'BLK', 'PF', 'TO']
grouped_matches = team_results.groupby('GAME_ID')[sum_columns].sum().reset_index()
# Calculate the team stats
matches = matches.merge(grouped_matches, on='GAME_ID', suffixes=('', '_GAME'))
# Calculate winners
winner_team = team_results.loc[team_results.groupby('GAME_ID')['PTS'].idxmax()]
winner_team = winner_team[['GAME_ID', 'TEAM_ID']]
# Calculate additional statistics
# Count statistics only if number of attemps is not empty
matches['FGM_2'] = matches.apply(calculate_not_empty, axis=1, args=['FGA', 'FGM'])
matches['FG3M_2'] = matches.apply(calculate_not_empty, axis=1, args=['FG3A', 'FG3M'])
matches['FTM_2'] = matches.apply(calculate_not_empty, axis=1, args=['FTA', 'FTM'])
# Count how many statistics were in double digits and calculate if it was a Double-Double or Triple-Double
matches['Stats_over_10'] = matches.apply(calculate_over_10, axis=1)
matches['DD'] = matches['Stats_over_10'].apply(lambda x: 1 if x >= 2 else 0)
matches['TD'] = matches['Stats_over_10'].apply(lambda x: 1 if x >= 3 else 0)
# Calculate the fantasy points, PIE and if player played in the match
matches['FP'] = matches.apply(calculate_fantasy_points, axis=1)
matches['GP'] = matches['MIN'].notna().astype(int)
matches['PIE'] =matches.apply(calculate_pie, axis=1)
# Calculate if team won the match
matches = matches.merge(winner_team, on='GAME_ID', how='left', suffixes=('', '_WINNER'))
matches['W'] = (matches['TEAM_ID'] == matches['TEAM_ID_WINNER']).astype(int) * matches['GP']
matches['L'] = (matches['TEAM_ID'] != matches['TEAM_ID_WINNER']).astype(int) * matches['GP']
matches = matches.drop(columns=['TEAM_ID_WINNER'])
# Calculate the seasonal stats
seasonal_stats = (matches.groupby(['SEASON', 'MATCH_TYPE', 'PLAYER_NAME',
'PLAYER_ID'])[['GP', 'W', 'L', 'MIN', 'PTS', 'REB', 'AST', 'STL', 'BLK', 'TO', 'FGM',
'FGA', 'FG3M', 'FG3A', 'FTM', 'FTA', 'FGM_2', 'FG3M_2', 'FTM_2',
'DD', 'TD', 'FP', 'PIE']].sum().reset_index())
# Calculate the percentages
seasonal_stats['FG_PCT'] = round(seasonal_stats['FGM_2'] / seasonal_stats['FGA'], 4)
seasonal_stats['FG3_PCT'] = round(seasonal_stats['FG3M_2'] / seasonal_stats['FG3A'], 4)
seasonal_stats['FT_PCT'] = round(seasonal_stats['FTM_2'] / seasonal_stats['FTA'], 4)
# Save the data
seasonal_stats.to_csv("data/seasonal_stats.csv", index=False)
def add_information_about_awards():
seasonal_stats = pd.read_csv("data/seasonal_stats.csv")
awards = pd.read_csv("data/nba_player_awards.csv")
# Drop rows with awards that were given only for limited time or are not related to a season
awards = awards[~awards['SUBTYPE1'].isin(['Hall of Fame', 'Sporting News', 'Olympic', 'IBM', 'All-Star'])]
# Add columns to the seasonal_stats dataframe
seasonal_stats['MVP'] = 0
seasonal_stats['ROY'] = 0
seasonal_stats['DPOY'] = 0
seasonal_stats['MIP'] = 0
seasonal_stats['6MOY'] = 0
seasonal_stats['All-NBA-Team'] = 0
seasonal_stats['All-Defensive-Team'] = 0
seasonal_stats['All-Rookie-Team'] = 0
seasonal_stats['All-Star'] = 0
seasonal_stats['All-Star-MVP'] = 0
seasonal_stats['Finals-MVP'] = 0
seasonal_stats['POTW'] = 0
seasonal_stats['POTM'] = 0
seasonal_stats['ROTM'] = 0
#print(awards['DESCRIPTION'].unique())
for index, row in awards.iterrows():
if row['DESCRIPTION'] == 'All-NBA':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'All-NBA-Team'] = row['ALL_NBA_TEAM_NUMBER']
if row['DESCRIPTION'] == 'NBA All-Star Most Valuable Player':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'All-Star-MVP'] = 1
if row['DESCRIPTION'] == 'All-Rookie Team':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'All-Rookie-Team'] = row['ALL_NBA_TEAM_NUMBER']
if row['DESCRIPTION'] == 'NBA Most Valuable Player':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'MVP'] = 1
if row['DESCRIPTION'] == 'NBA Rookie of the Year':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'ROY'] = 1
if row['DESCRIPTION'] == 'All-Defensive Team':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'All-Defensive-Team'] = row['ALL_NBA_TEAM_NUMBER']
if row['DESCRIPTION'] == 'NBA Rookie of the Month':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'ROTM'] += 1
if row['DESCRIPTION'] == 'NBA Player of the Month':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'POTM'] += 1
if row['DESCRIPTION'] == 'NBA Player of the Week':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'POTW'] += 1
if row['DESCRIPTION'] == 'NBA Defensive Player of the Year':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'DPOY'] = 1
if row['DESCRIPTION'] == 'NBA Most Improved Player':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'MIP'] = 1
if row['DESCRIPTION'] == 'NBA Sixth Man of the Year':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'6MOY'] = 1
# Go through the All-Star games and write information who took part in them
for index, row in seasonal_stats.iterrows():
if row['MATCH_TYPE'] == 'All-Star':
seasonal_stats.loc[(seasonal_stats['SEASON'] == row['SEASON']) & (seasonal_stats['PLAYER_ID'] == row['PLAYER_ID']),
'All-Star'] = 1
seasonal_stats.to_csv("data/seasonal_stats_with_awards.csv", index=False)
if __name__ == "__main__":
#prepare_matches()
#calculate_seasonal_stats()
add_information_about_awards()