-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse_elf_game_participation.py
227 lines (184 loc) · 7.58 KB
/
parse_elf_game_participation.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
222
223
224
225
226
227
import json
import logging
from datetime import datetime
import numpy as np
import pandas as pd
from tqdm import tqdm
from elf_utils import get_csv_in_folder, get_json_in_folder
def parse_elf_game_participation(season: int, save=False):
"""
"""
now = datetime.now()
filter_by_season = False
if season == 0:
pass
elif season > now.year:
raise ValueError(f'`season` cannot be greater than {now.year}.')
elif season < 2021:
raise ValueError('`season` cannot be less than 2021.')
else:
filter_by_season = True
json_file_list = get_json_in_folder()
participation_df = pd.DataFrame()
row_df = pd.DataFrame()
# print(json_file_list)
for json_file in tqdm(json_file_list):
with open(json_file, 'r') as f:
json_string = f.read()
# print(f'\n{json_file}')
json_data = json.loads(json_string)
try:
check = json_data["status"]
except Exception:
check = 200
try:
check = json_data["statusCode"]
except Exception as e:
logging.info(
"No `statusCode` present in this JSON file. " +
f"Full exception `{e}`"
)
if check == 200:
game_id = json_data['venue']['_attributes']['gameid']
game_date = str(json_data['venue']['_attributes']['date'])
if "." in game_date:
game_date = datetime.strptime(
game_date, '%m.%d.%Y'
)
else:
try:
game_date = datetime.strptime(
game_date, '%m/%d/%Y'
)
except Exception:
game_date = datetime.strptime(
f"{game_date}/{season}", '%m/%d/%Y'
)
game_season = game_date.year
home_id = json_data['venue']['_attributes']['homeid']
home_name = json_data['venue']['_attributes']['homename']
visitor_id = json_data['venue']['_attributes']['visid']
visitor_name = json_data['venue']['_attributes']['visname']
for i in json_data['visitor_players']:
# print(i['_attributes']['name'])
row_df = pd.DataFrame(
{
'season': game_season,
'game_id': game_id,
'team_id': visitor_id,
'team_name': visitor_name,
'loc': 'A',
'opponent_id': home_id,
'opponent_name': home_name
},
index=[0]
)
if str(i['_attributes']['name']).lower() != 'team' \
and str(i['_attributes']['name']).lower() != 'tm':
row_df['player_uni'] = i['_attributes']['uni']
row_df['player_name'] = i['_attributes']['name']
row_df['player_short_name'] = i['_attributes']['shortname']
row_df['player_check_name'] = i['_attributes']['checkname']
row_df['player_GP'] = i['_attributes']['gp']
try:
row_df['player_GS'] = int(i['_attributes']['gs'])
except Exception as e:
logging.info(
"Could not find any evidence " +
"that this player started this game. " +
f"Full exception `{e}`"
)
row_df['player_GS'] = 0
try:
row_df['player_pos'] = i['_attributes']['opos']
except Exception:
try:
row_df['player_pos'] = i['_attributes']['dpos']
except Exception as e:
logging.info(
"Could not find a position for this player. " +
f"Full exception `{e}`"
)
row_df['player_pos'] = None
participation_df = pd.concat(
[participation_df, row_df],
ignore_index=True
)
del row_df
for i in json_data['visitor_players']:
row_df = pd.DataFrame(
{
'season': game_season,
'game_id': game_id,
'opponent_id': home_id,
'opponent_name': home_name,
'loc': 'A',
'team_id': visitor_id,
'team_name': visitor_name
},
index=[0]
)
if str(i['_attributes']['name']).lower() != 'team' \
and str(i['_attributes']['name']).lower() != 'tm':
row_df['player_uni'] = i['_attributes']['uni']
row_df['player_name'] = i['_attributes']['name']
row_df['player_short_name'] = i['_attributes']['shortname']
row_df['player_check_name'] = i['_attributes']['checkname']
row_df['player_GP'] = i['_attributes']['gp']
try:
row_df['player_GS'] = int(i['_attributes']['gs'])
except Exception:
row_df['player_GS'] = 0
try:
row_df['player_pos'] = i['_attributes']['opos']
except Exception:
try:
row_df['player_pos'] = i['_attributes']['dpos']
except Exception:
row_df['player_pos'] = None
participation_df = pd.concat(
[participation_df, row_df],
ignore_index=True
)
del row_df
# Roster Data (to map player IDs)
roster_file_list = get_csv_in_folder('rosters/')
all_rosters_df = pd.DataFrame()
r_df = pd.DataFrame()
for roster_file in roster_file_list:
r_df = pd.read_csv(roster_file)
all_rosters_df = pd.concat([all_rosters_df, r_df], ignore_index=True)
del r_df
all_rosters_df = all_rosters_df[[
'season', 'player_id', 'old_player_id', 'team', 'player_short_name'
]]
all_rosters_df = all_rosters_df.rename(columns={'team': 'team_name'})
participation_df = pd.merge(
participation_df,
all_rosters_df,
how='left',
on=['season', 'team_name', 'player_short_name']
)
del all_rosters_df
if filter_by_season is True:
participation_df = participation_df.loc[
participation_df['season'] == season
]
if save is True:
seasons_arr = participation_df['season'].to_numpy()
seasons_arr = np.unique(seasons_arr)
for s in seasons_arr:
season_df = participation_df.loc[participation_df['season'] == s]
season_df.to_csv(
f'player_info/participation_data/{s}_elf_participation.csv',
index=False
)
# season_df.to_parquet(
# f'player_info/participation_data/{s}_elf_participation.parquet',
# index=False
# )
# print(participation_df)
return participation_df
if __name__ == "__main__":
now = datetime.now()
parse_elf_game_participation(now.year, True)