-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSparkPlayground_FlightDelayPrediction.py
1856 lines (1399 loc) · 68.1 KB
/
SparkPlayground_FlightDelayPrediction.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
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Databricks notebook source
# MAGIC %md ## Spark Playground - Flight Delay Status Classification
# MAGIC ##### Machine Learning At Scale (Spark, Spark ML)
# MAGIC Chenlin Ye, Hongsuk Nam, Swati Akella
# COMMAND ----------
# MAGIC %md ### Project Formulation
# MAGIC
# MAGIC Flight delays create problems in scheduling for airlines and airports, leading to passenger inconvenience, and huge economic losses. As a result, there is growing interest in predicting flight delays beforehand in order to optimize operations and improve customer satisfaction. The objective of this playground project is to predict flight departure delays two hours ahead of departure at scale. A delay is defined as 15-minute delay or greater with respect to the planned time of departure. Given that the target variable is a label of value 0 (no-delay) or 1 (delay), we framed this as a classification problem. In order to justify an accurately performing model suitable for the business purpose, false positive rate can be an effective model evaluation metrics. Throughout the project, we explore a series of data transformation and ML pipelines in Spark and conclude with challenges faced and key lessons learned.
# MAGIC
# MAGIC Datasets used in the project include the following:
# MAGIC - flight dataset from the [US Department of Transportation](https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236&DB_Short_Name=On-Time) containing flight information from 2015 to 2019
# MAGIC <br>**(31,746,841 x 109 dataframe)**
# MAGIC - weather dataset from the [National Oceanic and Atmospheric Administration repository](https://www.ncdc.noaa.gov/orders/qclcd/) containing weather information from 2015 to 2019
# MAGIC <br>**(630,904,436 x 177 dataframe)**
# MAGIC - airport dataset from the [US Department of Transportation](https://www.transtats.bts.gov/DL_SelectFields.asp)
# MAGIC <br>**(18,097 x 10 dataframe)**
# COMMAND ----------
# MAGIC %md ### Environment Set-up
# COMMAND ----------
from pyspark.sql.types import StructType, StructField, StringType, DoubleType, IntegerType, NullType
from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.feature import StandardScaler, Imputer
from pyspark.sql import functions as f
from pyspark.sql.window import Window
from pyspark.sql import SQLContext
import pyspark.ml.feature as ftr
import pyspark.ml as ml
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.classification import GBTClassifier
from pyspark.mllib.linalg.distributed import RowMatrix
from pyspark.ml.tuning import ParamGridBuilder
from pyspark.ml.tuning import CrossValidator
from pyspark.ml.tuning import TrainValidationSplit
from pyspark.ml import PipelineModel
from pyspark.mllib.linalg import Vectors
from pyspark.ml.feature import PCA
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from pyspark.ml import Pipeline
sqlContext = SQLContext(sc)
# COMMAND ----------
# MAGIC %md ### Data Extraction
# COMMAND ----------
# MAGIC %md ##### Data directory
# COMMAND ----------
# Data directory
DATA_PATH = "dbfs:/mnt/mids-w261/data/datasets_final_project/"
# Create file path
# dbutils.fs.mkdirs('dbfs:/mnt/w261/team22')
FILE_PATH = 'dbfs:/mnt/w261/team22/'
display(dbutils.fs.ls(DATA_PATH))
# COMMAND ----------
# Weather data
display(dbutils.fs.ls(DATA_PATH+"weather_data"))
# COMMAND ----------
# MAGIC %md ##### Load flight data
# COMMAND ----------
# Airline data
airlines = spark.read.option("header", "true").parquet(DATA_PATH+"parquet_airlines_data/*.parquet")
# Check the number of records loaded
f'{airlines.count():,}'
# COMMAND ----------
display(airlines)
# COMMAND ----------
# MAGIC %md ##### Load weather data
# COMMAND ----------
# Weather data
weather = spark.read.option("header", "true").parquet(DATA_PATH+"weather_data/*.parquet")
# # Check the number of records loaded
f'{weather.count():,}'
# COMMAND ----------
display(weather)
# COMMAND ----------
# MAGIC %md ##### Load airport data
# COMMAND ----------
file_location = "/FileStore/tables/193498910_T_MASTER_CORD.csv"
file_type = "csv"
infer_schema = "true"
first_row_is_header = "true"
delimiter = ","
airport = spark.read.format(file_type).option("inferSchema", infer_schema).option("header", first_row_is_header).option("sep", delimiter).load(file_location)
display(airport)
# COMMAND ----------
# MAGIC %md ### Data Transformation
# COMMAND ----------
# MAGIC %md ##### Airport Data
# COMMAND ----------
# MAGIC %md Filter down to US airports only
# COMMAND ----------
# function to filter down to US airport only
# remove duplicates (original dataset uses polygon to represent some airports; one point each airport is sufficient for us)
def airport_transform(dataframe):
return (
dataframe
.filter("AIRPORT_COUNTRY_CODE_ISO = 'US'")
.dropDuplicates(['AIRPORT'])
)
# COMMAND ----------
# tranform
airport = airport_transform(airport)
display(airport)
# COMMAND ----------
# MAGIC %md Keep airports that co-exist in the airline dataset
# COMMAND ----------
# spark sql
airlines.createOrReplaceTempView('airlines')
airport.createOrReplaceTempView('airport')
airport = spark.sql(
"""
SELECT *
FROM
airport
WHERE
AIRPORT IN (
SELECT DISTINCT ORIGIN FROM airlines
UNION
SELECT DISTINCT DEST FROM airlines
)
"""
)
# COMMAND ----------
# MAGIC %md ##### Check point - Transformed airport data
# MAGIC - This parquet check point contains airports that co-exist in the airlines dataset
# COMMAND ----------
# Write to parquet
#dbutils.fs.rm(FILE_PATH + "airport_cleaned.parquet", recurse=True)
# airport.write.parquet(FILE_PATH + "airport_cleaned.parquet")
# COMMAND ----------
# Read from parquet
airport = spark.read.option("header", "true").parquet(FILE_PATH+"airport_cleaned.parquet")
airport.createOrReplaceTempView('airport')
f'{airport.count():,}'
# COMMAND ----------
# MAGIC %md ##### Transforming airline Data
# MAGIC - The below columns from the airlines dataset were determinted to impact flight delay.
# COMMAND ----------
# Airlines transformation function
def airlines_transform(dataframe):
# Selected Columns
selected_col = [
"YEAR",
"QUARTER",
"MONTH",
"DAY_OF_MONTH",
"DAY_OF_WEEK",
"FL_DATE",
"OP_UNIQUE_CARRIER",
"TAIL_NUM",
"OP_CARRIER_FL_NUM",
"ORIGIN",
"ORIGIN_CITY_NAME",
"ORIGIN_STATE_ABR",
"DEST",
"DEST_CITY_NAME",
"DEST_STATE_ABR",
"CRS_DEP_TIME",
"CRS_DEP_TIME_HOUR",
"DEP_TIME_HOUR",
"DEP_DELAY_NEW",
"DEP_TIME_BLK",
"CRS_ARR_TIME",
"CRS_ARR_TIME_HOUR",
"ARR_TIME_HOUR",
"ARR_DELAY_NEW",
"ARR_TIME_BLK",
"DISTANCE",
"DISTANCE_GROUP",
"DEP_DEL15",
"ARR_DEL15",
"ORIGIN_AIRPORT_ID",
"DEST_AIRPORT_ID",
"CRS_DEP_TIMESTAMP",
"CRS_ARR_TIMESTAMP",
"PR_ARR_DEL15"]
# Creating a window partition to extract prior arrival delay for each flight
windowSpec = Window.partitionBy("TAIL_NUM").orderBy("CRS_DEP_TIMESTAMP")
return (
dataframe
.filter("CANCELLED != 1 AND DIVERTED != 1")
.withColumn("FL_DATE", f.col("FL_DATE").cast("date"))
.withColumn("OP_CARRIER_FL_NUM", f.col("OP_CARRIER_FL_NUM").cast("string"))
.withColumn("DEP_TIME_HOUR", dataframe.DEP_TIME_BLK.substr(1, 2).cast("int"))
.withColumn("ARR_TIME_HOUR", dataframe.ARR_TIME_BLK.substr(1, 2).cast("int"))
.withColumn("CRS_DEP_TIME_HOUR", f.round((f.col("CRS_DEP_TIME")/100)).cast("int"))
.withColumn("CRS_ARR_TIME_HOUR", f.round((f.col("CRS_ARR_TIME")/100)).cast("int"))
.withColumn("DISTANCE_GROUP", f.col("DISTANCE_GROUP").cast("string"))
.withColumn("OP_CARRIER_FL_NUM", f.concat(f.col("OP_CARRIER"),f.lit("_"),f.col("OP_CARRIER_FL_NUM")))
.withColumn("DEP_DEL15", f.col("DEP_DEL15").cast("string"))
.withColumn("ARR_DEL15", f.col("ARR_DEL15").cast("string"))
.withColumn("FL_DATE_string", f.col("FL_DATE").cast("string"))
.withColumn("YEAR", f.col("YEAR").cast("string"))
.withColumn("QUARTER", f.col("QUARTER").cast("string"))
.withColumn("MONTH", f.col("MONTH").cast("string"))
.withColumn("DAY_OF_MONTH", f.col("DAY_OF_MONTH").cast("string"))
.withColumn("DAY_OF_WEEK", f.col("DAY_OF_WEEK").cast("string"))
.withColumn("CRS_DEP_TIME_string", f.col("CRS_DEP_TIME").cast("string"))
.withColumn("CRS_ARR_TIME_string", f.col("CRS_ARR_TIME").cast("string"))
.withColumn("CRS_DEP_TIME_HOUR_string", f.col("CRS_DEP_TIME_HOUR").cast("string"))
.withColumn("CRS_ARR_TIME_HOUR_string", f.col("CRS_ARR_TIME_HOUR").cast("string"))
.withColumn("CRS_DEP_TIME_HH", f.lpad("CRS_DEP_TIME_string", 4, '0').substr(1,2))
.withColumn("CRS_DEP_TIME_MM", f.lpad("CRS_DEP_TIME_string", 4, '0').substr(3,2))
.withColumn("CRS_ARR_TIME_HH", f.lpad("CRS_ARR_TIME_string", 4, '0').substr(1,2))
.withColumn("CRS_ARR_TIME_MM", f.lpad("CRS_ARR_TIME_string", 4, '0').substr(3,2))
.withColumn("CRS_DEP_TIMESTAMP", f.concat(f.col("FL_DATE_string"),f.lit(" "),f.col("CRS_DEP_TIME_HH"), f.lit(":"),f.col("CRS_DEP_TIME_MM")).cast("timestamp"))
.withColumn("CRS_ARR_TIMESTAMP", f.concat(f.col("FL_DATE_string"),f.lit(" "),f.col("CRS_ARR_TIME_HH"), f.lit(":"),f.col("CRS_ARR_TIME_MM")).cast("timestamp"))
.withColumn("CRS_ELAPSED_TIME", f.round((f.col("CRS_ELAPSED_TIME")/60)).cast("int"))
.withColumn("PR_ARR_DEL15", f.lag(f.col("ARR_DEL15"), 1).over(windowSpec).cast("string"))
.select(selected_col)
)
# COMMAND ----------
# Transform
airlines = airlines_transform(airlines)
# COMMAND ----------
# MAGIC %md ##### Check point - transformed airlines data
# COMMAND ----------
# write to parquet
# dbutils.fs.rm(FILE_PATH + "airlines_cleaned.parquet", recurse=True)
# airlines.write.parquet(FILE_PATH + "airlines_cleaned.parquet")
# COMMAND ----------
# Read from parquet
airlines = spark.read.option("header", "true").parquet(FILE_PATH+"airlines_cleaned.parquet")
airlines.createOrReplaceTempView('airlines')
f'{airlines.count():,}'
# COMMAND ----------
display(airlines)
# COMMAND ----------
# MAGIC %md ##### Transforming Weather Data
# MAGIC The weather dataset contains columns and rows that do not pertain to aviation. We narrowed down the dataset using five transformation steps.
# COMMAND ----------
# MAGIC %md ##### Transforming weather data - part 1
# MAGIC - Filter weather dataset to US and Report Type "FM-15"
# COMMAND ----------
# Filter out US only
# Keep weather records for FM15 report type
def weather_transformation_reduction(dataframe, shorlisted_weather_cols):
return (
dataframe
.withColumn("COUNTRY", f.substring(f.col("NAME"), -2, 2))
.filter("COUNTRY = 'US'")
.filter("REPORT_TYPE LIKE '%FM-15%'")
.select(shorlisted_weather_cols)
)
shorlisted_weather_cols = ["STATION", "DATE", "LATITUDE", 'LONGITUDE', 'NAME', 'REPORT_TYPE', 'CALL_SIGN', 'WND', 'CIG', 'VIS', 'TMP', 'DEW', 'SLP', 'AA1', 'AJ1', 'AT1', 'GA1', 'IA1', 'MA1']
# COMMAND ----------
# MAGIC %md ##### Check point - transformed weather data
# MAGIC - US and FM-15 report type
# COMMAND ----------
# Writing to Parquet
# dbutils.fs.rm(FILE_PATH + "weather_us.parquet", recurse=True)
# weather_transformation_reduction(weather, shorlisted_weather_cols).write.parquet(FILE_PATH + "weather_us.parquet")
# COMMAND ----------
weather = spark.read.option("header", "true").parquet(FILE_PATH+"weather_us.parquet")
weather.createOrReplaceTempView('weather')
# COMMAND ----------
# MAGIC %md ##### Transforming weather data - part 2
# MAGIC - Keep station records that co-exist in the airport dataset
# COMMAND ----------
airport = spark.read.option("header", "true").parquet(FILE_PATH+"airport_cleaned.parquet")
# create sql view
airport.createOrReplaceTempView('airport')
# COMMAND ----------
# MAGIC %md Weather station to airport spatial join - so each airport can have a closest weather station id attached
# COMMAND ----------
# weather stations table with coordinates
weather_coordinates = spark.sql(
"""
SELECT
DISTINCT STATION, CALL_SIGN, LATITUDE, LONGITUDE
FROM
weather
"""
)
# COMMAND ----------
weather_coordinates = spark.read.option("header", "true").parquet(FILE_PATH + "weather_stations.parquet")
weather_coordinates_pdf = weather_coordinates.toPandas()
#weather_coordinates_pdf
# COMMAND ----------
airport_pdf = airport.toPandas()
airport_pdf
# COMMAND ----------
# Eclidean Distance calculation
X_coordinates = airport_pdf[['LATITUDE', 'LONGITUDE']]
Y_coordinates = weather_coordinates_pdf[['LATITUDE', 'LONGITUDE']]
weather_station_idx = metrics.pairwise_distances_argmin_min(X_coordinates, Y_coordinates, metric='euclidean')[0]
weather_station_idx
# COMMAND ----------
station_id = [weather_coordinates_pdf.iloc[i]['STATION'] for i in weather_station_idx]
station_id_weather_filter = spark.createDataFrame(station_id,StringType())
station_id_weather_filter.createOrReplaceTempView('station_id_weather_filter')
# COMMAND ----------
# MAGIC %md ##### Check point - transformed weather data
# MAGIC - weather data with stations co-exist in the airport dataset
# COMMAND ----------
dbutils.fs.rm(FILE_PATH + "weather_us_stations.parquet", recurse=True)
weather = weather.where(f.col("STATION").isin(set(station_id)))
# Write to parquet
weather.write.parquet(FILE_PATH + "weather_us_stations.parquet")
# Create SQL View
weather.createOrReplaceTempView('weather')
# COMMAND ----------
weather = spark.read.option("header", "true").parquet(FILE_PATH+"weather_us_stations.parquet")
weather.createOrReplaceTempView('weather')
# COMMAND ----------
display(weather)
# COMMAND ----------
# MAGIC %md ##### Transforming weather data - part 3
# MAGIC - Weather feature extraction and tarnsformation
# MAGIC - Extract relevant features that would affect to the airline delay.
# MAGIC - Fill missing and erroneous values with Null.
# MAGIC - Parsed out substrings into new columns.
# MAGIC - Assign erroneous data which codes are 3 and 7 to "999" which indicates missing values.
# MAGIC - Drop unnecessary columns.
# COMMAND ----------
def weather_transformation(dataframe):
return (
dataframe
# Mandatory data section - WND - Create substring columns to parse out values delimited by ","
.withColumn("WND_temp", f.substring_index("WND", ",", -2))\
.withColumn("WND_SPEED", f.substring_index("WND_temp", ",", 1))\
.withColumn("WND_SPEED_QUALITY", f.substring_index("WND_temp", ",", -1))\
# Filter out erroneous data
.withColumn("WND_SPEED_QUALITY", f.when((f.col("WND_SPEED_QUALITY") == "3") | (f.col("WND_SPEED_QUALITY") == "7") , "999").otherwise(f.col("WND_SPEED_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("WND_SPEED", f.when((f.col("WND_SPEED") == "") | (f.col("WND_SPEED") == "9999") | (f.col("WND_SPEED_QUALITY") == "999"), None).otherwise(f.col("WND_SPEED")))\
# Drop unnecessary columns
.drop("WND_temp","WND", "WND_SPEED_QUALITY")\
# Mandatory data section - CIG - Create substring columns to parse out multiple values delimited by ","
.withColumn("CIG_CAVOC", f.substring_index("CIG", ",", -1))\
# Change missing values to Null
.withColumn("CIG_CAVOC", f.when((f.col("CIG_CAVOC") == "") | (f.col("CIG_CAVOC") == "9"), None).otherwise(f.col("CIG_CAVOC")))\
# Drop unnecessary columns
.drop("CIG")\
# Mandatory data section - VIS - Create substring columns to parse out multiple values delimited by ","
.withColumn("VIS_temp", f.substring_index("VIS", ",", 2))\
.withColumn("VIS_DISTANCE", f.substring_index("VIS_temp", ",", 1))\
.withColumn("VIS_DISTANCE_QUALITY", f.substring_index("VIS_temp", ",", -1))\
# Filter out erroneous data
.withColumn("VIS_DISTANCE_QUALITY", f.when((f.col("VIS_DISTANCE_QUALITY") == "3") | (f.col("VIS_DISTANCE_QUALITY") == "7"), "999").otherwise(f.col("VIS_DISTANCE_QUALITY")))\
# Fill/Change the missing values to Null
.withColumn("VIS_DISTANCE", f.when((f.col("VIS_DISTANCE") == "") | (f.col("VIS_DISTANCE") == "999999") | (f.col("VIS_DISTANCE_QUALITY") == "999"), None).otherwise(f.col("VIS_DISTANCE")))\
# Drop unnecessary columns
.drop("VIS_temp", "VIS_DISTANCE_QUALITY", "VIS")\
# Mandatory data section - TMP - Create substring columns to parse out multiple values delimited by ","
.withColumn("TMP_TEMP", f.substring_index("TMP", ",", 1))\
.withColumn("TMP_TEMP_QUALITY", f.substring_index("TMP", ",", -1))\
# Filter out erroneous data
.withColumn("TMP_TEMP_QUALITY", f.when((f.col("TMP_TEMP_QUALITY") == "3") | (f.col("TMP_TEMP_QUALITY") == "7"), "999").otherwise(f.col("TMP_TEMP_QUALITY")))\
# Fill/Change the missing values to Null
.withColumn("TMP_TEMP", f.when((f.col("TMP_TEMP") == "") | (f.col("TMP_TEMP") == "+9999") | (f.col("TMP_TEMP_QUALITY") == "999"), None).otherwise(f.col("TMP_TEMP")))\
# Drop unnecessary columns
.drop("TMP_TEMP_QUALITY", "TMP")\
# Mandatory data section - DEW - Create substring columns to parse out multiple values delimited by ","
.withColumn("DEW_TEMP", f.substring_index("DEW", ",", 1))\
.withColumn("DEW_TEMP_QUALITY", f.substring_index("DEW", ",", -1))\
# Filter out erroneous data
.withColumn("DEW_TEMP_QUALITY", f.when((f.col("DEW_TEMP_QUALITY") == "3") | (f.col("DEW_TEMP_QUALITY") == "7"), "999").otherwise(f.col("DEW_TEMP_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("DEW_TEMP", f.when((f.col("DEW_TEMP") == "") | (f.col("DEW_TEMP") == "+9999") | (f.col("DEW_TEMP_QUALITY") == "999"), None).otherwise(f.col("DEW_TEMP")))\
# Drop unnecessary columns
.drop("DEW_TEMP_QUALITY", "DEW")\
# Mandatory data section - SLP - Create substring columns to parse out multiple values delimited by ","
.withColumn("SLP_PRESSURE", f.substring_index("SLP", ",", 1))\
.withColumn("SLP_PRESSURE_QUALITY", f.substring_index("SLP", ",", -1))\
# Filter out erroneous data
.withColumn("SLP_PRESSURE_QUALITY", f.when((f.col("SLP_PRESSURE_QUALITY") == "3") | (f.col("SLP_PRESSURE_QUALITY") == "7"), "999").otherwise(f.col("SLP_PRESSURE_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("SLP_PRESSURE", f.when((f.col("SLP_PRESSURE") == "") | (f.col("SLP_PRESSURE") == "99999") | (f.col("SLP_PRESSURE_QUALITY") == "999"), None).otherwise(f.col("SLP_PRESSURE")))\
# Drop unnecessary columns
.drop("SLP_PRESSURE_QUALITY", "SLP" )\
# Additional data section - AA1 - Create substring columns to parse out multiple values delimited by ","
.withColumn("AA1_temp", f.substring_index("AA1", ",", -3))\
.withColumn("PRECIPITATION", f.substring_index("AA1_temp", ",", 1))\
.withColumn("PRECIPITATION_QUALITY", f.substring_index("AA1_temp", ",", -1))\
# Filter out erroneous data
.withColumn("PRECIPITATION_QUALITY", f.when((f.col("PRECIPITATION_QUALITY") == "3") | (f.col("PRECIPITATION_QUALITY") == "7"), "999").otherwise(f.col("PRECIPITATION_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("PRECIPITATION", f.when((f.col("PRECIPITATION") == "") | (f.col("PRECIPITATION") == "9999") | (f.col("PRECIPITATION_QUALITY") == "999"), None).otherwise(f.col("PRECIPITATION")))\
# Drop unnecessary columns
.drop("AA1_temp", "AA1", "PRECIPITATION_QUALITY")\
# Additional data section - AJ1 - Create substring columns to parse out multiple values delimited by ","
.withColumn("AJ1_temp", f.substring_index("AJ1", ",", 3))\
.withColumn("SNOW", f.substring_index("AJ1_temp", ",", 1))\
.withColumn("SNOW_QUALITY", f.substring_index("AJ1_temp", ",", -1))\
# Filter out erroneous data
.withColumn("SNOW_QUALITY", f.when((f.col("SNOW_QUALITY") == "3") | (f.col("SNOW_QUALITY") == "7"), "999").otherwise(f.col("SNOW_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("SNOW", f.when((f.col("SNOW") == "") | (f.col("SNOW") == "9999") | (f.col("SNOW_QUALITY") == "999"), None).otherwise(f.col("SNOW")))\
# Drop unnecessary columns
.drop("AJ1_temp", "AJ1", "SNOW_QUALITY")\
# Additional data section - AT1 - Create substring columns to parse out multiple values delimited by ","
.withColumn("AT1_temp", f.substring_index("AT1", ",", -3))\
.withColumn("WEATHER_OBSERVATION", f.substring_index("AT1_temp", ",", 1))\
.withColumn("WEATHER_OBSERVATION_QUALITY", f.substring_index("AT1_temp", ",", -1))\
# Filter out erroneous data
.withColumn("WEATHER_OBSERVATION_QUALITY", f.when((f.col("WEATHER_OBSERVATION_QUALITY") == "3") | (f.col("WEATHER_OBSERVATION_QUALITY") == "7"), "999").otherwise(f.col("WEATHER_OBSERVATION_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("WEATHER_OBSERVATION", f.when((f.col("WEATHER_OBSERVATION") == "") | (f.col("WEATHER_OBSERVATION_QUALITY") == "999"), None).otherwise(f.col("WEATHER_OBSERVATION")))\
# Drop unnecessary columns
.drop("AT1", "AT1_temp", "WEATHER_OBSERVATION_QUALITY")\
# Additional data section - GA1 - Create substring columns to parse out multiple values delimited by ","
.withColumn("GA1_temp", f.substring_index("GA1", ",", 4))\
.withColumn("GA1_temp2", f.substring_index("GA1_temp", ",", 2))\
.withColumn("GA1_temp3", f.substring_index("GA1_temp", ",", -2))\
.withColumn("CLOUD_COVERAGE", f.substring_index("GA1_temp2", ",", 1))\
.withColumn("CLOUD_COVERAGE_QUALITY", f.substring_index("GA1_temp2", ",", -1))\
# Filter out erroneous data
.withColumn("CLOUD_COVERAGE_QUALITY", f.when((f.col("CLOUD_COVERAGE_QUALITY") == "3") | (f.col("CLOUD_COVERAGE_QUALITY") == "7"), "999").otherwise(f.col("CLOUD_COVERAGE_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("CLOUD_COVERAGE", f.when((f.col("CLOUD_COVERAGE") == "") | (f.col("CLOUD_COVERAGE") == "99") | (f.col("CLOUD_COVERAGE") == "9") | (f.col("CLOUD_COVERAGE") == "10") | (f.col("CLOUD_COVERAGE_QUALITY") == "999"), None).otherwise(f.col("CLOUD_COVERAGE")))\
# Drop unnecessary columns
.drop("GA1", "GA1_temp", "GA1_temp2", "CLOUD_COVERAGE_QUALITY")\
# Additional data section - GA1 - Create substring columns to parse out multiple values delimited by ","
.withColumn("CLOUD_BASE_HEIGHT", f.substring_index("GA1_temp3", ",", 1))\
.withColumn("CLOUD_BASE_HEIGHT_QUALITY", f.substring_index("GA1_temp3", ",", -1))\
# Filter out erroneous data
.withColumn("CLOUD_BASE_HEIGHT_QUALITY", f.when((f.col("CLOUD_BASE_HEIGHT_QUALITY") == "3") | (f.col("CLOUD_BASE_HEIGHT_QUALITY") == "7"), "999").otherwise(f.col("CLOUD_BASE_HEIGHT_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("CLOUD_BASE_HEIGHT", f.when((f.col("CLOUD_BASE_HEIGHT") == "") | (f.col("CLOUD_BASE_HEIGHT") == "+99999") | (f.col("CLOUD_BASE_HEIGHT_QUALITY") == "999"), None).otherwise(f.col("CLOUD_BASE_HEIGHT")))\
# Drop unnecessary columns
.drop("GA1_temp3", "CLOUD_BASE_HEIGHT_QUALITY")\
# Additional data section - IA1 - Create substring columns to parse out multiple values delimited by ","
.withColumn("GROUND_SURFACE", f.substring_index("IA1", ",", 1))\
.withColumn("GROUND_SURFACE_QUALITY", f.substring_index("IA1", ",", -1))\
# Filter out erroneous data
.withColumn("GROUND_SURFACE_QUALITY", f.when(f.col("GROUND_SURFACE_QUALITY") == "3", "999").otherwise(f.col("GROUND_SURFACE_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("GROUND_SURFACE", f.when((f.col("GROUND_SURFACE") == "") | (f.col("GROUND_SURFACE") == "99") | (f.col("GROUND_SURFACE_QUALITY") == "999"), None).otherwise(f.col("GROUND_SURFACE")))\
# Drop unnecessary columns
.drop("IA1", "GROUND_SURFACE_QUALITY" )\
# Additional data section - MA1 - Create substring columns to parse out multiple values delimited by ","
.withColumn("MA1_temp", f.substring_index("MA1", ",", 2))\
.withColumn("ALTIMETER_SET", f.substring_index("MA1_temp", ",", 1))\
.withColumn("ALTIMETER_SET_QUALITY", f.substring_index("MA1_temp", ",", -1))\
# Filter out erroneous data
.withColumn("ALTIMETER_SET_QUALITY", f.when((f.col("ALTIMETER_SET_QUALITY") == "3") | (f.col("ALTIMETER_SET_QUALITY") == "7"), "999").otherwise(f.col("ALTIMETER_SET_QUALITY")))\
# Fill/Change missing values to Null
.withColumn("ALTIMETER_SET", f.when((f.col("ALTIMETER_SET") == "") | (f.col("ALTIMETER_SET") == "99999") | (f.col("ALTIMETER_SET_QUALITY") == "999"), None).otherwise(f.col("ALTIMETER_SET")))\
# Drop unnecessary columns
.drop("MA1", "MA1_temp", "ALTIMETER_SET_QUALITY")
)
# COMMAND ----------
# MAGIC %md ##### Check point - weather with transformed features
# COMMAND ----------
# transform
weather = weather_transformation(weather)
# save to parquet
dbutils.fs.rm(FILE_PATH + "weather_column_transform.parquet", recurse=True)
weather.write.parquet(FILE_PATH + "weather_column_transform.parquet")
# COMMAND ----------
# read from parquet
weather = spark.read.option("header", "true").parquet(FILE_PATH+"weather_column_transform.parquet")
weather.createOrReplaceTempView('weather')
# COMMAND ----------
# MAGIC %md ##### Transforming weather data - part 4
# MAGIC - Weather data UTC time to local time conversion to match with airline dataset which uses local time zone
# COMMAND ----------
# Function to obtain timezone IDs from coordinates
def get_timezone(longitude, latitude):
from timezonefinder import TimezoneFinder
tzf = TimezoneFinder()
return tzf.timezone_at(lng=longitude, lat=latitude)
# Initiate udf function
udf_timezone = f.udf(get_timezone, StringType())
# transform
weather = weather.withColumn("LOCAL", udf_timezone(weather.LONGITUDE, weather.LATITUDE))
# COMMAND ----------
# Converting UTC timezone to Local timezone
weather = weather.withColumn("LOCAL_DATE", f.from_utc_timestamp(f.col("DATE"), weather.LOCAL))
# COMMAND ----------
# Create new columns in weather data, parsing out timestamps
weather = weather.withColumn("DATE_PART", f.to_date(f.col("LOCAL_DATE")))\
.withColumn("HOUR_PART", f.hour(f.col("LOCAL_DATE")).cast("int"))\
.withColumn("MINUTE_PART", f.minute(f.col("LOCAL_DATE")).cast("int"))\
.withColumn("CALL_SIGN", f.trim(f.col("CALL_SIGN")))\
.drop("LOCAL", "LOCAL_DATE")
# COMMAND ----------
# MAGIC %md ##### Check point - weather with converted timestamps
# COMMAND ----------
#write to parquet
dbutils.fs.rm(FILE_PATH + "weather_timestamp.parquet", recurse=True)
weather.write.parquet(FILE_PATH + "weather_timestamp.parquet")
# COMMAND ----------
# read from parquet
weather = spark.read.option("header", "true").parquet(FILE_PATH+"weather_timestamp.parquet")
weather.createOrReplaceTempView('weather')
# COMMAND ----------
# MAGIC %md ##### Transforming weather data - part 5
# MAGIC - Weather data type casting
# COMMAND ----------
# data type casting
cast_columns = ["WND_SPEED", "VIS_DISTANCE", "TMP_TEMP", "DEW_TEMP", "SLP_PRESSURE", "PRECIPITATION", "SNOW", "CLOUD_COVERAGE", "CLOUD_BASE_HEIGHT", "ALTIMETER_SET"]
for c in cast_columns:
weather = weather.withColumn(c, weather[c].cast("int"))
# COMMAND ----------
display(weather)
# COMMAND ----------
# MAGIC %md ##### Check point - Weather with converted timestamps and appropriate data type
# COMMAND ----------
# write to parquet
dbutils.fs.rm(FILE_PATH + "weather_timestamp_wCasting.parquet", recurse=True)
weather.write.parquet(FILE_PATH + "weather_timestamp_wCasting.parquet")
# read from parquet
weather = spark.read.option("header", "true").parquet(FILE_PATH+"weather_timestamp_wCasting.parquet")
weather.createOrReplaceTempView('weather')
# COMMAND ----------
# MAGIC %md ### Table join
# MAGIC In order to make logical connections between the weather dataset and the airlines dataset, we would need to join the two datasets together with the airport dataset as the helper table.
# MAGIC - Identify the nearest (in Euclidean distance) weather station to each airport so that each airport record has a corresponding weather station ID
# MAGIC - Join the airport dataset to the airlines dataset (on airport code) so that each departing flight has a corresponding weather station ID
# MAGIC - Bring scheduled departure timestamp for each flight to 2 hours prior so that we can obtain weather information at least 2 hours prior to departure (weather timestamp in UTC already converted to local timestamps in the previous section)
# MAGIC - Join the weather dataset to the airlines dataset on the following conditions:
# MAGIC - matching weather station ID
# MAGIC - for each tiemstamp (2-hour prior to scheduled departure) in the airlines dataset, join by the nearest timestamp in the weather dataset
# COMMAND ----------
# MAGIC %md ##### Weather station to airport join
# COMMAND ----------
# Create station id list based on the statation id index generated from the Euclidean distance calculation
station_id = [weather_coordinates_pdf.iloc[i]['STATION'] for i in weather_station_idx]
# Create weather_station_id column in the airport dataset with corresponding station id
airport_pdf['weather_station_id'] = station_id
# Convert airport dataframe from pandas to Spark
airport = spark.createDataFrame(airport_pdf)
# create sql view
airport.createOrReplaceTempView('airport')
display(airport)
# COMMAND ----------
# MAGIC %md ##### Airport to airline join
# COMMAND ----------
# spark sql - airport to airlines join
airlines = spark.sql(
"""
SELECT
airline.*,
airport_origin.LATITUDE AS ORIGIN_LATITUDE,
airport_origin.LONGITUDE AS ORIGIN_LONGITUDE,
airport_origin.weather_station_id AS weather_station,
airport_destination.LATITUDE AS DESTINATION_LATITUDE,
airport_destination.LONGITUDE AS DESTINATION_LONGITUDE
FROM
airlines airline
LEFT JOIN airport airport_origin
ON airline.ORIGIN = airport_origin.AIRPORT
LEFT JOIN airport airport_destination
ON airline.DEST = airport_destination.AIRPORT
"""
)
display(airlines)
# COMMAND ----------
# MAGIC %md ##### Check point - airlines with airport information
# COMMAND ----------
# write to parquet
dbutils.fs.rm(FILE_PATH + "airlines_wairport.parquet", recurse=True)
airlines.write.parquet(FILE_PATH + "airlines_wairport.parquet")
# COMMAND ----------
# Read from parquet
airlines = spark.read.option("header", "true").parquet(FILE_PATH+"airlines_wairport.parquet")
airlines.createOrReplaceTempView('airlines')
f'{airlines.count():,}'
# COMMAND ----------
# MAGIC %md ##### Weather to airline join
# COMMAND ----------
# MAGIC %md Create two-hour prior timestamps for airlines based on scheduled departure times
# COMMAND ----------
# Bring scheduled departure time to 2 hours prior
airlines = airlines.withColumn('TWO_HOUR', airlines.CRS_DEP_TIMESTAMP + f.expr('INTERVAL -2 HOURS'))
display(airlines)
# COMMAND ----------
# MAGIC %md Create timestamp usind date/hour/minute part
# COMMAND ----------
weather = weather.withColumn("AL_JOIN_DATE", f.col("DATE_PART").cast("string"))\
.withColumn("AL_JOIN_HOUR", f.col("HOUR_PART").cast("string"))\
.withColumn("AL_JOIN_MINUTE", f.col("MINUTE_PART").cast("string"))\
.withColumn("AL_JOIN_TIMESTAMP", f.concat(f.col("AL_JOIN_DATE"),f.lit(" "),f.col("AL_JOIN_HOUR"), f.lit(":"),f.col("AL_JOIN_MINUTE")).cast("timestamp"))
# COMMAND ----------
# Create helper timestamp column for the airlines to weather join
# Convert timestamp to unix for better performance
# Reduce ThisTimeStamp by a second to avoid overlapping ranges during join
windowSpecJoin = Window.partitionBy("STATION").orderBy("AL_JOIN_TIMESTAMP")
weather_test = weather.withColumn("ThisTimeStamp", f.unix_timestamp(f.col("AL_JOIN_TIMESTAMP"))).withColumn("NextTimeStamp", f.lead(f.col("ThisTimeStamp"), 1).over(windowSpecJoin) -1)
# COMMAND ----------
# Convert airlines timestamp to unix for airlines to weather join.
airlines_temp_join = airlines.withColumn("AL_ThisTimeStamp", f.unix_timestamp(f.col("TWO_HOUR")))
# COMMAND ----------
display(airlines_temp_join)
# COMMAND ----------
# MAGIC %md Weather to airlines left join
# MAGIC - matching Station ID
# MAGIC - nearest timestamp partition by station ID for each tiemstamp in airlines
# COMMAND ----------
airlines_temp_join.repartition(363, "weather_station").createOrReplaceTempView('airlines_temp_join')
weather_test.repartition(363, "STATION").createOrReplaceTempView('weather_test')
airlines_weather_leftjoin = spark.sql("""
SELECT a.*, w.*
FROM
airlines_temp_join a
LEFT JOIN weather_test w
ON
a.weather_station = w.STATION
AND a.AL_ThisTimeStamp BETWEEN w.ThisTimeStamp AND w.NextTimeStamp
"""
)
# COMMAND ----------
display(airlines_weather_leftjoin)
# COMMAND ----------
# MAGIC %md ##### Check point - Joined airlines and weather data (Final check point for joined airlines & weather data)
# COMMAND ----------
# write to parquet
dbutils.fs.rm(FILE_PATH + "airlines_weather_leftjoin.parquet", recurse=True)
airlines_weather_leftjoin.repartition(10).write.parquet(FILE_PATH + "airlines_weather_leftjoin.parquet")
# COMMAND ----------
# Read from parquet
airlines_weather = spark.read.option("header", "true").parquet(FILE_PATH+"airlines_weather_leftjoin.parquet")
airlines_weather.createOrReplaceTempView('airlines_weather')
f'{airlines_weather.count():,}'
# COMMAND ----------
# MAGIC %md ### Sample EDA with pyspark and SparkSQL
# MAGIC
# MAGIC On a dataset level, the airlines dataset has a fairly even distribution across the years. However, the dataset has over four times of on-time records than delayed ones (based on the ```DEP_DEL15``` label). This would introduce a class imbalance issue during the model training phase.
# MAGIC
# MAGIC Secondly, on a feature level, the distribution of continuous features would inform us the optimal imputation methods during the ML pipeline. Normally distributed features (i.e. Altimeter Set, SLP pressure, Dew temperature) are more suitable for average value imputation. Similarly, skewed features (i.e. Snow level, wind speed, cloud base height) are more suitable for median imputation.
# MAGIC
# MAGIC Through looking at the percentage of delayed flights grouped by various feature groupings, we can see that:
# MAGIC - Not all carriers are created equal: some suffers more delays than others
# MAGIC - Not all airports are created equal: some suffers more delays than others
# MAGIC - Seasonally trends exist: more delays during summer months and holiday seasons
# MAGIC - Temporal trends exist: more delays during the afternoons and evenings
# MAGIC - Arrival delays and departure delays track very closely to each other (potential for creating a new feature that tracks each flight's previous flight's arrival delay status)
# COMMAND ----------
airlines_weather.printSchema()
# COMMAND ----------
# Checking the number of records under each year
display(airlines_weather.select("YEAR", "DEP_DEL15")
.groupBy("YEAR")
.agg({"DEP_DEL15": "COUNT"})
.withColumn("Count Of Records", f.col("count(DEP_DEL15)"))
.orderBy("YEAR")
.drop("count(DEP_DEL15)"))
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Check for class imbalance
# MAGIC SELECT
# MAGIC DEP_DEL15,
# MAGIC COUNT(DEP_DEL15) AS Count
# MAGIC FROM
# MAGIC airlines_weather
# MAGIC GROUP BY
# MAGIC DEP_DEL15
# MAGIC ORDER BY
# MAGIC DEP_DEL15 DESC
# COMMAND ----------
# MAGIC %md ##### Feature histogram
# COMMAND ----------
numericCols = [feature for (feature, dataType) in airlines_weather.dtypes if ((dataType == "int") & (feature != "DEP_DEL15"))]
feature_hist_df = airlines_weather.select(numericCols).toPandas()
feature_hist_df.hist(figsize=(20, 20), bins=30)
plt.show()
# COMMAND ----------
target_features = [
"CRS_DEP_TIME_HOUR",
"DEP_DELAY_NEW",
"CRS_ARR_TIME_HOUR",
"ARR_DELAY_NEW",
"DISTANCE",
"WND_SPEED",
"VIS_DISTANCE",
"TMP_TEMP",
"DEW_TEMP",
"SLP_PRESSURE",
"PRECIPITATION",
"SNOW",
"CLOUD_COVERAGE",
"CLOUD_BASE_HEIGHT",
"ALTIMETER_SET"
]
corr = airlines_weather.select(target_features).toPandas().corr()
# COMMAND ----------
# MAGIC %md ##### Correlation matrix
# COMMAND ----------
# Plotting the correlation matrix
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
cmap = sns.diverging_palette(240, 10, as_cmap=True)
fig, ax = plt.subplots(figsize=(20,10))
sns.heatmap(corr, mask=mask, cmap=cmap, center=0, linewidths=.5)
# COMMAND ----------
# MAGIC %md ##### Arrival and departure delay
# COMMAND ----------
# MAGIC %md Percent delay by Carrier
# MAGIC * Not all carriers are created equally
# MAGIC * Arrival delays and departure delays track each other closely
# MAGIC * % departure delays tend to be higher than arrival delays when grouped by most other features, but some carriers tend to have higher arrival delays
# COMMAND ----------
# MAGIC %sql
# MAGIC -- percent delay by carrier
# MAGIC SELECT
# MAGIC OP_UNIQUE_CARRIER AS Carrier,
# MAGIC AVG(DEP_DEL15) AS PercentDepartureDelay,
# MAGIC AVG(ARR_DEL15) AS PercentArrivalDelay
# MAGIC FROM
# MAGIC airlines_weather
# MAGIC GROUP BY
# MAGIC OP_UNIQUE_CARRIER
# MAGIC ORDER BY
# MAGIC 2 DESC
# COMMAND ----------
# MAGIC %md Percent delay of day of week
# MAGIC * Mid-week and Saturdays tend to have least amount of delays; Mondays tend to be the worst.
# COMMAND ----------
# MAGIC %sql
# MAGIC -- percent delay by day of week
# MAGIC SELECT
# MAGIC DAY_OF_WEEK AS DOW,
# MAGIC AVG(DEP_DEL15) AS PercentDepartureDelay,
# MAGIC AVG(ARR_DEL15) AS PercentArrivalDelay
# MAGIC FROM
# MAGIC airlines_weather
# MAGIC GROUP BY
# MAGIC 1
# MAGIC ORDER BY
# MAGIC 1
# COMMAND ----------
# MAGIC %md Percent delay by month
# MAGIC * When we have the entire airlines dataset, it'd interesting to see if seasonality has any influence on delays
# COMMAND ----------
# MAGIC %sql
# MAGIC SELECT
# MAGIC -- percent delay by month
# MAGIC MONTH AS Month,
# MAGIC AVG(DEP_DEL15) AS PercentDepartureDelay,
# MAGIC AVG(ARR_DEL15) AS PercentArrivalDelay
# MAGIC FROM
# MAGIC airlines_weather
# MAGIC GROUP BY
# MAGIC 1
# MAGIC ORDER BY
# MAGIC MONTH
# COMMAND ----------
# MAGIC %md Percent delay by actual departure/arrival time
# COMMAND ----------
# MAGIC %sql
# MAGIC -- percent delay by actual departure/arrival time block
# MAGIC WITH departure AS (
# MAGIC SELECT
# MAGIC DEP_TIME_BLK AS TimeBlock,
# MAGIC AVG(DEP_DEL15) AS PercentDepartureDelay
# MAGIC FROM
# MAGIC airlines_weather