-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFeatureEngineering.py
More file actions
599 lines (426 loc) · 25.1 KB
/
Copy pathFeatureEngineering.py
File metadata and controls
599 lines (426 loc) · 25.1 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
Importing necessary libraries and modules.
import warnings
import numpy as np
import pandas as pd
from collections import OrderedDict
from InputData import loadDataFrameList
warnings.filterwarnings('ignore')
## Loading the list of dataframes from DataPreprocessing.
DataFrames = loadDataFrameList()
'''----------------------------------- Adding Fifa Ratings --------------------------------------------'''
## Creating a function that adds the scraped fifa ratings to the dataframe.
def addFifaRatings(DataFrame):
## Reading in the fifa ratings file.
fifaRatings = pd.read_csv('./Log.csv', sep = ',')
## Singling out the season currently under observation.
currSeason = DataFrame.Season.unique()[0]
## Isolating the respective season fifa ratings.
fifaRatingsIsolated = fifaRatings[ fifaRatings['Season'] == currSeason]
## Initialsing the values in the coloumns for the Fifa Team Rankings .
DataFrame['AOverall'] = np.nan
DataFrame['HOverall'] = np.nan
DataFrame['AAttack'] = np.nan
DataFrame['HAttack'] = np.nan
DataFrame['AMidfield'] = np.nan
DataFrame['HMidfield'] = np.nan
DataFrame['ADefense'] = np.nan
DataFrame['HDefense'] = np.nan
## Creating a list of all the teams that played in that season (Non-Standard).
TeamsNS = list((DataFrame).HomeTeam.unique())
TeamsNS = sorted(TeamsNS, key = str.lower)
## Creating a list of all the teams that played in that season (Standard).
TeamsS = list((fifaRatingsIsolated).Name.unique())
TeamsS = sorted(TeamsS, key = str.lower)
## Replacing the non-standard names by the standard names in the dataframe.
DataFrame = DataFrame.replace(TeamsNS, TeamsS)
## Creating a Temporary DataFrame which consists of the records of the matches teamwise .
for z in range(0, 20):
## Creating a Temporary DataFrame where the team was either "Home" or "Away" .
tempDF = DataFrame[ (DataFrame['HomeTeam'] == str(TeamsS[z]) ) | ( DataFrame['AwayTeam'] == str(TeamsS[z])) ]
## Parsing the attributes for the particular team under observation.
infoRow = fifaRatingsIsolated[fifaRatingsIsolated['Name'] == TeamsS[z]]
Overall = infoRow['Overall']
Defense = infoRow['Defense']
MidField = infoRow['Midfield']
Attack = infoRow['Attack']
## Creating a list for the index values of the games contained in the tempDF.
gameIndices = tempDF.index.tolist()
## Creating two lists which contains the index number of those games wherein the team under observation was Home or Away.
indexHome = []
indexAway = []
## Segregate home and away match indices.
for index, row in tempDF.iterrows():
if (TeamsS[z] == row['HomeTeam']):
indexHome.append(index)
elif (TeamsS[z] == row['AwayTeam']):
indexAway.append(index)
## Appending the appropriate "KPP" values to the dataframe.
for j in range(0, 38):
if (gameIndices[j] in indexHome):
DataFrame['HOverall'][gameIndices[j]] = Overall
DataFrame['HAttack'][gameIndices[j]] = Attack
DataFrame['HMidfield'][gameIndices[j]] = MidField
DataFrame['HDefense'][gameIndices[j]] = Defense
elif (gameIndices[j] in indexAway):
DataFrame['AOverall'][gameIndices[j]] = Overall
DataFrame['AAttack'][gameIndices[j]] = Attack
DataFrame['AMidfield'][gameIndices[j]] = MidField
DataFrame['ADefense'][gameIndices[j]] = Defense
## Filling in the coloumns for "Overall, Attack, Midfield and Defense".
DataFrame['Overall'] = DataFrame.apply(lambda row: row['HOverall'] - row['AOverall'], axis = 1)
DataFrame['Attack'] = DataFrame.apply(lambda row: row['HAttack'] - row['AAttack'], axis = 1)
DataFrame['Midfield'] = DataFrame.apply(lambda row: row['HMidfield'] - row['AMidfield'], axis = 1)
DataFrame['Defense'] = DataFrame.apply(lambda row: row['HDefense'] - row['ADefense'], axis = 1)
return DataFrame
'''----------------------------------- Adding Goal Difference as a Feature --------------------------------------------'''
## Creating a function that computes the columns "HTGD" ( Home Team Goal Difference ) and "ATGD" ( Away Team Goal Difference ) .
def computeTGD(DataFrame) :
## Initialising the values contained in the coloumns "HTGD" and "ATGD" . (Goal Difference)
DataFrame['HTGD'] = np.nan
DataFrame['ATGD'] = np.nan
## Creating a list of all the teams that played in that season .
Teams = list((DataFrame).HomeTeam.unique())
## Creating a Temporary DataFrame which consists of the records of the matches teamwise .
for z in range(0, 20):
## Creating a Temporary DataFrame where the team was either "Home" or "Away" .
tempDF = DataFrame[ (DataFrame['HomeTeam'] == str(Teams[z]) ) | ( DataFrame['AwayTeam'] == str(Teams[z])) ]
## Creating a list which contains "Matchwise Goal Difference" for the team under observation .
MGDList = []
for index, row in tempDF.iterrows():
if (Teams[z] == row['HomeTeam']):
MGDList.append(row['MHTGD'])
elif (Teams[z] == row['AwayTeam']):
MGDList.append(row['MATGD'])
## Creating a list which contains "Goal Difference" for the team under observation before coming into each match.
GDList = []
for i in range(0, 38):
## When the team has played no match.
if (i == 0):
GDList.append(0)
## When the team has played exactly one match.
elif (i == 1):
GDList.append(MGDList[i - 1])
## When the team has played more than 1 match.
else:
GDList.append(GDList[i - 1] + MGDList[i - 1])
## We will now normalise the Goal Difference.
for m in range(0, 38):
GDList[m] /= 100
## Creating a list for the index values of the games contained in tempDF.
gameIndices = tempDF.index.tolist()
## Creating two lists which contains the index number of those games wherein the team under observation was Home or Away.
indexHome = []
indexAway = []
for index, row in tempDF.iterrows():
## If team was Home Team.
if (Teams[z] == row['HomeTeam']):
indexHome.append(index)
## If team was Away Team.
elif (Teams[z] == row['AwayTeam']):
indexAway.append(index)
## Appending the appropriate "Goal Difference" values to the dataframe .
for j in range(0, 38):
if (gameIndices[j] in indexHome):
DataFrame['HTGD'][gameIndices[j]] = GDList[j]
elif (gameIndices[j] in indexAway):
DataFrame['ATGD'][gameIndices[j]] = GDList[j]
## Filling in the coloumns for "GD".
DataFrame['GD'] = DataFrame.apply(lambda row: row['HTGD'] - row['ATGD'], axis = 1)
''''----------------------------------- Adding KPP as a Feature --------------------------------------------'''
## Creating a function which computes the KPP (K-Past Performance) feature for Goals, Corners and Shots on Target.
def computeKPP(DataFrame, slidingWindowParameter):
## Set slidingWindowParameter to k.
k = slidingWindowParameter
## Creating a list of all the teams that played in that season.
Teams = list((DataFrame).HomeTeam.unique())
## Initialising the values contained in the coloumns "HGKPP , HCKPP , HSTKPP" and "AGKPP , ACKPP , ASTKPP". (KPP Features).
DataFrame['HGKPP'] = np.nan
DataFrame['AGKPP'] = np.nan
DataFrame['HCKPP'] = np.nan
DataFrame['ACKPP'] = np.nan
DataFrame['HSTKPP'] = np.nan
DataFrame['ASTKPP'] = np.nan
## Creating a Temporary DataFrame which consists of the records of the matches teamwise.
for z in range(0, 20):
## Creating a Temporary DataFrame where the team was either "Home" or "Away" .
tempDF = DataFrame[(DataFrame['HomeTeam'] == str(Teams[z])) | ( DataFrame['AwayTeam'] == str(Teams[z]))]
## Creating a list which contains Goals, Corners and Number of Shots on Target for the team under observation match-wise.
Goals = []
Corners = []
shotsonTarget = []
for index, row in tempDF.iterrows():
if (Teams[z] == row['HomeTeam']):
Goals.append(float(row['FTHG']))
Corners.append(float(row['HC']))
shotsonTarget.append(float(row['HST']))
elif (Teams[z] == row['AwayTeam']):
Goals.append(float(row['FTAG']))
Corners.append(float(row['AC']))
shotsonTarget.append(float(row['AST']))
## Creating lists to hold values for the corresponding KPP Features.
# Since these features will be non existent for the first k matches of each team, fill Nan for the first k values.
goalsKPP = [np.nan] * k
cornersKPP = [np.nan] * k
shotsOnTargetKPP = [np.nan] * k
## Adding appropriate values to the list.
## The number of computations performed will be (n + 1 - k) where :
## n = number of matches in the season for each team (38).
## k = sliding window hyper-parameter.
for i in range(0, (39 - k)):
## Obtaining the slice of records to be observed.
## Sum the slice of records and normalize it by k.
goalSliceSum = sum(Goals[i : (i + k)])/k
cornerSliceSum = sum(Corners[i : (i + k)])/k
shotsOnTargetSliceSum = sum(shotsonTarget[i : (i + k)])/k
## Appending to the list of the corresponding KPP features.
goalsKPP.append(goalSliceSum)
cornersKPP.append(cornerSliceSum)
shotsOnTargetKPP.append(shotsOnTargetSliceSum)
## Creating a list for the index values of the games contained in the tempDF.
gameIndices = tempDF.index.tolist()
## Creating two lists which contains the index number of those games wherein the team under observation was Home or Away.
indexHome = []
indexAway = []
## Segregate home and away match indices.
for index, row in tempDF.iterrows():
if (Teams[z] == row['HomeTeam']):
indexHome.append(index)
elif (Teams[z] == row['AwayTeam']):
indexAway.append(index)
## Appending the appropriate "KPP" values to the dataframe.
for j in range(0, 38):
if (gameIndices[j] in indexHome):
DataFrame['HGKPP'][gameIndices[j]] = goalsKPP[j]
DataFrame['HCKPP'][gameIndices[j]] = cornersKPP[j]
DataFrame['HSTKPP'][gameIndices[j]] = shotsOnTargetKPP[j]
elif (gameIndices[j] in indexAway):
DataFrame['AGKPP'][gameIndices[j]] = goalsKPP[j]
DataFrame['ACKPP'][gameIndices[j]] = cornersKPP[j]
DataFrame['ASTKPP'][gameIndices[j]] = shotsOnTargetKPP[j]
## Filling in the coloumns for "GKPP, CKPP, STKPP".
DataFrame['GKPP'] = DataFrame.apply(lambda row: row['HGKPP'] - row['AGKPP'], axis = 1)
DataFrame['CKPP'] = DataFrame.apply(lambda row: row['HCKPP'] - row['ACKPP'], axis = 1)
DataFrame['STKPP'] = DataFrame.apply(lambda row: row['HSTKPP'] - row['ASTKPP'], axis = 1)
''''----------------------------------- Adding Streak and Weighted Streak as a Feature --------------------------------------------'''
## Creating a function which computes the Streak and Weighted Streak.
def computeStreak(DataFrame, slidingWindowParameter):
## Set slidingWindowParameter to k.
k = slidingWindowParameter
## Creating a list of all the teams that played in that season.
Teams = list((DataFrame).HomeTeam.unique())
## Initialsing the values in the coloumns "HSt, ASt , HStWeigted , AStWeigted".
DataFrame['HSt'] = np.nan
DataFrame['ASt'] = np.nan
DataFrame['HStWeighted'] = np.nan
DataFrame['AStWeighted'] = np.nan
## Creating a Temporary DataFrame which consists of the records of the matches teamwise.
for z in range(0, 20):
## Creating a Temporary DataFrame where the team was either "Home" or "Away" .
tempDF = DataFrame[(DataFrame['HomeTeam'] == str(Teams[z])) | ( DataFrame['AwayTeam'] == str(Teams[z]))]
## Creating a list which contains the points assigned to each team after their match.
## 0 - Loss
## 1 - Draw
## 3 - Win
matchPoints = []
## Creating a list which contains the weights assigned to each match according to the sliding window hyper-parameter.
## The weighting scheme is such that the first match in the window will be a assigned a weight of 1 and the last match will be
## assigned a weight of k.
weightList = [(i + 1) for i in range(0, k)]
for index , row in tempDF.iterrows():
if (Teams[z] == row['HomeTeam']):
if (row['FTR'] == 'A') :
matchPoints.append(0.0)
elif (row['FTR'] == 'D') :
matchPoints.append(1.0)
elif (row['FTR'] == 'H') :
matchPoints.append(3.0)
elif (Teams[z] == row['AwayTeam']):
if (row['FTR'] == 'H') :
matchPoints.append(0.0)
elif (row['FTR'] == 'D') :
matchPoints.append(1.0)
elif (row['FTR'] == 'A') :
matchPoints.append(3.0)
## Creating lists to hold values for the corresponding Streak and Weighted Streak Features.
## Since these features will be non existent for the first k matches of each team, fill Nan for the first k values.
streak = [np.nan] * k
weightedStreak = [np.nan] * k
## Adding appropriate values to the list.
## The number of computations performed will be (n + 1 - k) where :
## n = number of matches in the season for each team (38).
## k = sliding window hyper-parameter.
for i in range(0, (39 - k)):
## Obtaining the slice of records to be observed.
matchPointsSlice = matchPoints[i : (i + k)]
## Sum the slice of records and normalize it by 3k.
streakValue = sum(matchPointsSlice)/(3 * k)
## Multiply the slice by the weights.
## Sum the slice of records and normalize it by (3k(k+1))/2.
weightedStreakValue = sum(list(np.array(matchPointsSlice) * np.array(weightList)))/((1.5) * k * (k + 1))
## Appending to the list of the corresponding features.
streak.append(streakValue)
weightedStreak.append(weightedStreakValue)
## Creating a list for the index values of the games contained in the tempDF.
gameIndices = tempDF.index.tolist()
## Creating two lists which contains the index number of those games wherein the team under observation was Home or Away.
indexHome = []
indexAway = []
## Segregate home and away match indices.
for index, row in tempDF.iterrows():
if (Teams[z] == row['HomeTeam']):
indexHome.append(index)
elif (Teams[z] == row['AwayTeam']):
indexAway.append(index)
## Appending the appropriate "KPP" values to the dataframe.
for j in range(0, 38):
if (gameIndices[j] in indexHome):
DataFrame['HSt'][gameIndices[j]] = streak[j]
DataFrame['HStWeighted'][gameIndices[j]] = weightedStreak[j]
elif (gameIndices[j] in indexAway):
DataFrame['ASt'][gameIndices[j]] = streak[j]
DataFrame['AStWeighted'][gameIndices[j]] = weightedStreak[j]
## Filling in the coloumns for "Streak and WeightedStreak".
DataFrame['Streak'] = DataFrame.apply(lambda row: row['HSt'] - row['ASt'], axis = 1)
DataFrame['WeightedStreak'] = DataFrame.apply(lambda row: row['HStWeighted'] - row['AStWeighted'], axis = 1)
''''----------------------------------- Adding Form as a Feature --------------------------------------------'''
## Creating a function which computes the Form.
def computeForm(DataFrame, stealingFraction):
## Hyper-Parameter k.
k = stealingFraction
## Initialising the values contained in the coloumns "HForm" and "AForm".
DataFrame['HForm'] = 1.0
DataFrame['AForm'] = 1.0
## Creating a global form dictionary with keys as team names and value as list of form.
gFormDict = {}
## Creating a global form dictionary with keys as team names and value as list of match indices.
teamMatchLookup = {}
## Dictionary which keeps track of a team's match indices.
matchCounterDict = {}
## Creating a list of all the teams that played in that season .
Teams = list((dataFrame).HomeTeam.unique())
for teamName in Teams :
## Initialising values.
gFormDict[teamName] = 1.0
matchCounterDict[teamName] = 0
## For each team playing in the season, create a temporary dataframe to record the match numbers of each team.
## Create a temporary dataframe for the team under consideration.
tempDF = DataFrame[(DataFrame['HomeTeam'] == str(teamName)) | ( DataFrame['AwayTeam'] == str(teamName))]
## Assigning match indices list to the relevant team.
teamMatchLookup[teamName] = tempDF.index.tolist()
## Iterating over each match in the season.
for index, row in DataFrame.iterrows():
## Exit condition. Since the last update in the form values will be in the 2nd last match for each team, we have to run the loop till each team's 2nd last match.
## This condition happens at the 370th in each season.
if (index == 370):
break
## Update match counter for the playing teams.
matchCounterDict[row['HomeTeam']] += 1
matchCounterDict[row['AwayTeam']] += 1
## Case where home team wins. Since the home team wins here, a positive update is given to the home team and a negative update is given to the away team.
if (row['FTR'] == 'H'):
## Form values of the teams before coming into the match.
prevHomeForm = gFormDict[row['HomeTeam']]
prevAwayForm = gFormDict[row['AwayTeam']]
## Next match index of the Home and Away Team.
nextMatchH = teamMatchLookup[row['HomeTeam']][matchCounterDict[row['HomeTeam']]]
nextMatchA = teamMatchLookup[row['AwayTeam']][matchCounterDict[row['AwayTeam']]]
## Since the home team wins here, a positive update is given to the home team and a negative update is given to the away team.
homeUpdate = gFormDict[row['HomeTeam']] + k * gFormDict[row['AwayTeam']]
awayUpdate = gFormDict[row['AwayTeam']] - k * gFormDict[row['AwayTeam']]
## Selecting next match record for the current Home Team.
matchInfoH = DataFrame.iloc[[nextMatchH]]
## Check whether current Home Team is Home or Away in their next match and update Form accordingly.
if (matchInfoH['HomeTeam'][nextMatchH] == row['HomeTeam']):
DataFrame.loc[nextMatchH, 'HForm'] = homeUpdate
elif (matchInfoH['AwayTeam'][nextMatchH] == row['HomeTeam']):
DataFrame.loc[nextMatchH, 'AForm'] = homeUpdate
## Update value in the dictionary.
gFormDict[row['HomeTeam']] = homeUpdate
## Selecting next match record for the current Away Team.
matchInfoA = DataFrame.iloc[[nextMatchA]]
## Check whether current Away Team is Home or Away in their next match and update Form accordingly.
if (matchInfoA['HomeTeam'][nextMatchA] == row['AwayTeam']):
DataFrame.loc[nextMatchA, 'HForm'] = awayUpdate
elif (matchInfoA['AwayTeam'][nextMatchA] == row['AwayTeam']):
DataFrame.loc[nextMatchA, 'AForm'] = awayUpdate
## Update value in the dictionary.
gFormDict[row['AwayTeam']] = awayUpdate
## Case where away team wins. Since the away team wins here, a positive update is given to the away team and a negative update is given to the home team.
if (row['FTR'] == 'A'):
## Form values of the teams before coming into the match.
prevHomeForm = gFormDict[row['HomeTeam']]
prevAwayForm = gFormDict[row['AwayTeam']]
## Next match index of the Home and Away Team.
nextMatchH = teamMatchLookup[row['HomeTeam']][matchCounterDict[row['HomeTeam']]]
nextMatchA = teamMatchLookup[row['AwayTeam']][matchCounterDict[row['AwayTeam']]]
## Since the away team wins here, a positive update is given to the away team and a negative update is given to the home team.
homeUpdate = gFormDict[row['HomeTeam']] - k * gFormDict[row['HomeTeam']]
awayUpdate = gFormDict[row['AwayTeam']] + k * gFormDict[row['HomeTeam']]
## Selecting next match for the current Home Team.
matchInfoH = DataFrame.iloc[[nextMatchH]]
## Check whether current Home Team is Home or Away in their next match and update Form accordingly.
if (matchInfoH['HomeTeam'][nextMatchH] == row['HomeTeam']):
DataFrame.loc[nextMatchH, 'HForm'] = homeUpdate
elif (matchInfoH['AwayTeam'][nextMatchH] == row['HomeTeam']):
DataFrame.loc[nextMatchH, 'AForm'] = homeUpdate
## Update value in the dictionary.
gFormDict[row['HomeTeam']] = homeUpdate
## Selecting next match for the current Away Team.
matchInfoA = DataFrame.iloc[[nextMatchA]]
## Check whether current Away Team is Home or Away in their next match and update Form accordingly.
if (matchInfoA['HomeTeam'][nextMatchA] == row['AwayTeam']):
DataFrame.loc[nextMatchA, 'HForm'] = awayUpdate
elif (matchInfoA['AwayTeam'][nextMatchA] == row['AwayTeam']):
DataFrame.loc[nextMatchA, 'AForm'] = awayUpdate
## Update value in the dictionary.
gFormDict[row['AwayTeam']] = awayUpdate
## Case where a draw occurs.
if (row['FTR'] == 'D'):
# Form values of the teams before coming into the match.
prevHomeForm = gFormDict[row['HomeTeam']]
prevAwayForm = gFormDict[row['AwayTeam']]
## Next match index of the Home and Away Team.
nextMatchH = teamMatchLookup[row['HomeTeam']][matchCounterDict[row['HomeTeam']]]
nextMatchA = teamMatchLookup[row['AwayTeam']][matchCounterDict[row['AwayTeam']]]
## Form Updates.
homeUpdate = gFormDict[row['HomeTeam']] - k * ((gFormDict[row['HomeTeam']]) - (gFormDict[row['AwayTeam']]))
awayUpdate = gFormDict[row['AwayTeam']] - k * ((gFormDict[row['AwayTeam']]) - (gFormDict[row['HomeTeam']]))
## Selecting next match for the current Home Team.
matchInfoH = DataFrame.iloc[[nextMatchH]]
## Check whether current Home Team is Home or Away in their next match and update Form accordingly.
if (matchInfoH['HomeTeam'][nextMatchH] == row['HomeTeam']):
DataFrame.loc[nextMatchH, 'HForm'] = homeUpdate
elif (matchInfoH['AwayTeam'][nextMatchH] == row['HomeTeam']):
DataFrame.loc[nextMatchH, 'AForm'] = homeUpdate
## Update value in the dictionary.
gFormDict[row['HomeTeam']] = homeUpdate
## Selecting next match for the current Away Team.
matchInfoA = DataFrame.iloc[[nextMatchA]]
## Check whether current Away Team is Home or Away in their next match and update Form accordingly.
if (matchInfoA['HomeTeam'][nextMatchA] == row['AwayTeam']):
DataFrame.loc[nextMatchA, 'HForm'] = awayUpdate
elif (matchInfoA['AwayTeam'][nextMatchA] == row['AwayTeam']):
DataFrame.loc[nextMatchA, 'AForm'] = awayUpdate
## Update value in the dictionary.
gFormDict[row['AwayTeam']] = awayUpdate
# Filling in the coloumns for "Form".
DataFrame['Form'] = DataFrame.apply(lambda row: row['HForm'] - row['AForm'], axis = 1)
## Computing features for all the data.
for i, dataFrame in enumerate(DataFrames):
dataFrame['MHTGD'] = dataFrame.apply(lambda row: row['FTHG'] - row['FTAG'], axis = 1)
dataFrame['MATGD'] = dataFrame.apply(lambda row: row['FTAG'] - row['FTHG'], axis = 1)
## Computing the features.
computeTGD(dataFrame)
computeKPP(dataFrame, 6)
computeStreak(dataFrame, 6)
computeForm(dataFrame, 0.33)
print(i)
## Adding the fifa Ratings to all the dataframes.
dataFrameList = []
for dataFrame in DataFrames:
frameFifaRatings = addFifaRatings(dataFrame)
dataFrameList.append(frameFifaRatings)
## Concatening all the dataframes together.
DataFrame = pd.concat(dataFrameList)
## Saving the newly engineered dataset.
DataFrame.to_csv('./EngineeredData.csv', sep = ',', index = False)