-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBig Data Analytics.py
More file actions
1753 lines (1259 loc) · 48.8 KB
/
Copy pathBig Data Analytics.py
File metadata and controls
1753 lines (1259 loc) · 48.8 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
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
# MAGIC Install Kaggle package in a notebook cell
# COMMAND ----------
# MAGIC %pip install kaggle
# COMMAND ----------
# MAGIC %md
# MAGIC Set the Kaggle token in the notebook session
# COMMAND ----------
import os
if not os.environ.get("KAGGLE_API_TOKEN"):
raise ValueError("Set the KAGGLE_API_TOKEN environment variable before running this notebook.")
print("Kaggle token loaded from environment")
# COMMAND ----------
# MAGIC %md
# MAGIC Test whether Kaggle is working
# COMMAND ----------
!kaggle competitions list
# COMMAND ----------
!kaggle datasets list -s "airline delay cancellation"
# COMMAND ----------
# MAGIC %md
# MAGIC Download the dataset directly into Databricks
# COMMAND ----------
import os
download_dir = "/tmp/airline_delay_data"
os.makedirs(download_dir, exist_ok=True)
!kaggle datasets download -d yuanyuwendymu/airline-delay-and-cancellation-data-2009-2018 -p /tmp/airline_delay_data
# COMMAND ----------
# MAGIC %md
# MAGIC Unzip the dataset
# COMMAND ----------
import zipfile
zip_path = "/tmp/airline_delay_data/airline-delay-and-cancellation-data-2009-2018.zip"
extract_dir = "/tmp/airline_delay_data/unzipped"
os.makedirs(extract_dir, exist_ok=True)
with zipfile.ZipFile(zip_path, "r") as zip_ref:
zip_ref.extractall(extract_dir)
print("Files extracted:")
print(os.listdir(extract_dir))
# COMMAND ----------
# DBTITLE 1,Create Volume
# MAGIC %sql
# MAGIC CREATE VOLUME IF NOT EXISTS workspace.default.airline_data;
# COMMAND ----------
# MAGIC %md
# MAGIC Grant Access - No need to run this one - ALREADY GAVE ACCESS TO ALL USERS
# COMMAND ----------
# %sql
# -- Grant catalog access
# GRANT USE CATALOG ON CATALOG workspace TO `jakshiganj@gmail.com`;
# GRANT USE CATALOG ON CATALOG workspace TO `mpawickramasinghe@gmail.com`;
# GRANT USE CATALOG ON CATALOG workspace TO `sanjula.nelumdeniyage@gmail.com`;
# GRANT USE CATALOG ON CATALOG workspace TO `sewjithsilva@gmail.com`;
# GRANT USE CATALOG ON CATALOG workspace TO `shenonak15@gmail.com`;
# -- Grant schema access
# GRANT USE SCHEMA ON SCHEMA workspace.default TO `jakshiganj@gmail.com`;
# GRANT USE SCHEMA ON SCHEMA workspace.default TO `mpawickramasinghe@gmail.com`;
# GRANT USE SCHEMA ON SCHEMA workspace.default TO `sanjula.nelumdeniyage@gmail.com`;
# GRANT USE SCHEMA ON SCHEMA workspace.default TO `sewjithsilva@gmail.com`;
# GRANT USE SCHEMA ON SCHEMA workspace.default TO `shenonak15@gmail.com`;
# -- Grant volume read access
# GRANT READ VOLUME ON VOLUME workspace.default.airline_data TO `jakshiganj@gmail.com`;
# GRANT READ VOLUME ON VOLUME workspace.default.airline_data TO `mpawickramasinghe@gmail.com`;
# GRANT READ VOLUME ON VOLUME workspace.default.airline_data TO `sanjula.nelumdeniyage@gmail.com`;
# GRANT READ VOLUME ON VOLUME workspace.default.airline_data TO `sewjithsilva@gmail.com`;
# GRANT READ VOLUME ON VOLUME workspace.default.airline_data TO `shenonak15@gmail.com`;
# COMMAND ----------
import os
try: print(os.listdir("/Volumes/workspace/default/airline_data"))
except PermissionError:
print("Permission denied: cannot access the directory.")
# COMMAND ----------
df_2016 = spark.read.option("header", True).csv("/Volumes/workspace/default/airline_data/2016.csv")
df_2017 = spark.read.option("header", True).csv("/Volumes/workspace/default/airline_data/2017.csv")
df_2018 = spark.read.option("header", True).csv("/Volumes/workspace/default/airline_data/2018.csv")
display(df_2016.limit(5))
display(df_2017.limit(5))
display(df_2018.limit(5))
# COMMAND ----------
# MAGIC %md
# MAGIC Member 03
# COMMAND ----------
# MAGIC %md
# MAGIC Import required libraries
# COMMAND ----------
from pyspark.sql import functions as F
from pyspark.sql.types import *
# COMMAND ----------
# MAGIC %md
# MAGIC Load the required datasets
# COMMAND ----------
df_2016_raw = spark.read.csv(
"/Volumes/workspace/default/airline_data/2016.csv",
header=True,
inferSchema=True
)
df_2017_raw = spark.read.csv(
"/Volumes/workspace/default/airline_data/2017.csv",
header=True,
inferSchema=True
)
df_2018_raw = spark.read.csv(
"/Volumes/workspace/default/airline_data/2018.csv",
header=True,
inferSchema=True
)
print("2016 rows:", df_2016_raw.count())
print("2017 rows:", df_2017_raw.count())
print("2018 rows:", df_2018_raw.count())
# COMMAND ----------
# MAGIC %md
# MAGIC Standardise column names
# COMMAND ----------
def standardize_column_name(col_name):
return (
col_name.strip()
.lower()
.replace(" ", "_")
.replace("-", "_")
.replace("/", "_")
.replace("(", "")
.replace(")", "")
)
def standardize_columns(df):
return df.toDF(*[standardize_column_name(c) for c in df.columns])
df_2016_raw = standardize_columns(df_2016_raw)
df_2017_raw = standardize_columns(df_2017_raw)
df_2018_raw = standardize_columns(df_2018_raw)
# COMMAND ----------
# MAGIC %md
# MAGIC Select only the most relevant columns
# COMMAND ----------
selected_columns = [
"fl_date",
"op_unique_carrier",
"op_carrier_fl_num",
"origin",
"dest",
"crs_dep_time",
"dep_time",
"dep_delay",
"taxi_out",
"wheels_off",
"wheels_on",
"taxi_in",
"crs_arr_time",
"arr_time",
"arr_delay",
"cancelled",
"cancellation_code",
"diverted",
"crs_elapsed_time",
"actual_elapsed_time",
"air_time",
"distance",
"carrier_delay",
"weather_delay",
"nas_delay",
"security_delay",
"late_aircraft_delay"
]
def select_existing_columns(df, columns):
existing_cols = [c for c in columns if c in df.columns]
return df.select(*existing_cols)
df_2016 = select_existing_columns(df_2016_raw, selected_columns)
df_2017 = select_existing_columns(df_2017_raw, selected_columns)
df_2018 = select_existing_columns(df_2018_raw, selected_columns)
# COMMAND ----------
# MAGIC %md
# MAGIC Build reusable preprocessing function
# MAGIC This function will:
# MAGIC
# MAGIC remove duplicates;
# MAGIC calculate missing value percentages;
# MAGIC drop columns with more than 50% missing values;
# MAGIC fill numeric nulls with average;
# MAGIC fill categorical nulls with "Unknown";
# MAGIC cast important columns;
# MAGIC create derived features;
# COMMAND ----------
def preprocess_airline_data(df, year_label):
print(f"\n========== PREPROCESSING {year_label} ==========")
# 1. Remove duplicate rows
before_count = df.count()
df = df.dropDuplicates()
after_count = df.count()
print(f"{year_label} - Rows before duplicate removal: {before_count}")
print(f"{year_label} - Rows after duplicate removal : {after_count}")
print(f"{year_label} - Duplicate rows removed : {before_count - after_count}")
# 2. Rename key columns
rename_dict = {
"fl_date": "flight_date",
"op_unique_carrier": "airline",
"op_carrier_fl_num": "flight_number"
}
for old_name, new_name in rename_dict.items():
if old_name in df.columns:
df = df.withColumnRenamed(old_name, new_name)
# 3. Convert data types
cast_map = {
"dep_delay": "double",
"arr_delay": "double",
"cancelled": "int",
"diverted": "int",
"distance": "double",
"air_time": "double",
"crs_elapsed_time": "double",
"actual_elapsed_time": "double",
"carrier_delay": "double",
"weather_delay": "double",
"nas_delay": "double",
"security_delay": "double",
"late_aircraft_delay": "double",
"crs_dep_time": "int",
"dep_time": "int",
"crs_arr_time": "int",
"arr_time": "int",
"taxi_out": "double",
"taxi_in": "double"
}
for col_name, target_type in cast_map.items():
if col_name in df.columns:
df = df.withColumn(col_name, F.col(col_name).cast(target_type))
if "flight_date" in df.columns:
df = df.withColumn("flight_date", F.to_date("flight_date"))
# 4. Find missing value percentages
total_rows = df.count()
missing_percentage_exprs = []
for c in df.columns:
missing_percentage_exprs.append(
F.round(
(F.count(F.when(F.col(c).isNull(), c)) / F.lit(total_rows)) * 100, 2
).alias(c)
)
missing_percentage_df = df.select(missing_percentage_exprs)
print(f"{year_label} - Missing value percentages:")
display(missing_percentage_df)
missing_dict = missing_percentage_df.collect()[0].asDict()
# 5. Drop columns with > 50% missing values
cols_to_drop = [col_name for col_name, pct in missing_dict.items() if pct > 50]
print(f"{year_label} - Columns dropped (>50% missing): {cols_to_drop}")
df = df.drop(*cols_to_drop)
# 6. Identify numeric and categorical columns
numeric_types = ["int", "bigint", "double", "float", "decimal", "long", "smallint"]
numeric_cols = [c for c, dtype in df.dtypes if dtype in numeric_types]
categorical_cols = [c for c, dtype in df.dtypes if dtype not in numeric_types and c != "flight_date"]
# 7. Fill missing numeric values with average
for c in numeric_cols:
avg_value = df.select(F.avg(F.col(c))).collect()[0][0]
if avg_value is not None:
df = df.fillna({c: float(avg_value)})
# 8. Fill missing categorical values with Unknown
for c in categorical_cols:
df = df.fillna({c: "Unknown"})
# 9. Drop rows with critical missing values only if still present
critical_cols = [c for c in ["airline", "origin", "dest", "flight_date"] if c in df.columns]
df = df.dropna(subset=critical_cols)
# 10. Remove clearly invalid values
if "dep_delay" in df.columns:
df = df.filter((F.col("dep_delay") >= -200) & (F.col("dep_delay") <= 2000))
if "arr_delay" in df.columns:
df = df.filter((F.col("arr_delay") >= -200) & (F.col("arr_delay") <= 2000))
if "distance" in df.columns:
df = df.filter(F.col("distance") > 0)
if "air_time" in df.columns:
df = df.filter(F.col("air_time") >= 0)
# 11. Create derived columns
if "origin" in df.columns and "dest" in df.columns:
df = df.withColumn("route", F.concat_ws("-", F.col("origin"), F.col("dest")))
if "flight_date" in df.columns:
df = df.withColumn("year", F.year("flight_date")) \
.withColumn("month", F.month("flight_date")) \
.withColumn("day", F.dayofmonth("flight_date")) \
.withColumn("day_of_week", F.dayofweek("flight_date"))
if "crs_dep_time" in df.columns:
df = df.withColumn("crs_dep_time_str", F.lpad(F.col("crs_dep_time").cast("string"), 4, "0")) \
.withColumn("scheduled_dep_hour", F.substring("crs_dep_time_str", 1, 2).cast("int"))
if "arr_delay" in df.columns:
df = df.withColumn("is_delayed", F.when(F.col("arr_delay") > 15, 1).otherwise(0))
if "cancelled" in df.columns:
df = df.withColumn("flight_status", F.when(F.col("cancelled") == 1, "Cancelled").otherwise("Operated"))
if "arr_delay" in df.columns:
df = df.withColumn(
"delay_category",
F.when(F.col("arr_delay") <= 15, "On Time / Minor Delay")
.when((F.col("arr_delay") > 15) & (F.col("arr_delay") <= 60), "Moderate Delay")
.otherwise("Severe Delay")
)
if "month" in df.columns:
df = df.withColumn(
"month_name",
F.when(F.col("month") == 1, "Jan")
.when(F.col("month") == 2, "Feb")
.when(F.col("month") == 3, "Mar")
.when(F.col("month") == 4, "Apr")
.when(F.col("month") == 5, "May")
.when(F.col("month") == 6, "Jun")
.when(F.col("month") == 7, "Jul")
.when(F.col("month") == 8, "Aug")
.when(F.col("month") == 9, "Sep")
.when(F.col("month") == 10, "Oct")
.when(F.col("month") == 11, "Nov")
.otherwise("Dec")
)
# 12. Final missing value check
final_total_rows = df.count()
final_missing_exprs = []
for c in df.columns:
final_missing_exprs.append(
F.round(
(F.count(F.when(F.col(c).isNull(), c)) / F.lit(final_total_rows)) * 100, 2
).alias(c)
)
final_missing_df = df.select(final_missing_exprs)
print(f"{year_label} - Final missing value percentages after preprocessing:")
display(final_missing_df)
print(f"{year_label} - Final rows : {df.count()}")
print(f"{year_label} - Final columns: {len(df.columns)}")
return df
# COMMAND ----------
# MAGIC %md
# MAGIC Apply preprocessing separately to 2016, 2017, and 2018
# COMMAND ----------
df_2016_clean = preprocess_airline_data(df_2016, "2016")
df_2017_clean = preprocess_airline_data(df_2017, "2017")
df_2018_clean = preprocess_airline_data(df_2018, "2018")
# COMMAND ----------
# MAGIC %md
# MAGIC Preview cleaned data
# COMMAND ----------
print("===== CLEANED 2016 =====")
display(df_2016_clean.limit(5))
print("===== CLEANED 2017 =====")
display(df_2017_clean.limit(5))
print("===== CLEANED 2018 =====")
display(df_2018_clean.limit(5))
# COMMAND ----------
print("Preprocessing completed successfully.")
print("2016 cleaned rows:", df_2016_clean.count())
print("2017 cleaned rows:", df_2017_clean.count())
print("2018 cleaned rows:", df_2018_clean.count())
# COMMAND ----------
# MAGIC %md
# MAGIC Member 04
# MAGIC
# COMMAND ----------
# MAGIC %md
# MAGIC Import required libraries
# COMMAND ----------
from pyspark.sql import functions as F
from pyspark.sql.window import Window
# COMMAND ----------
# MAGIC %md
# MAGIC Combine all cleaned yearly datasets
# COMMAND ----------
df_2016_analysis = df_2016_clean.withColumn("dataset_year", F.lit(2016))
df_2017_analysis = df_2017_clean.withColumn("dataset_year", F.lit(2017))
df_2018_analysis = df_2018_clean.withColumn("dataset_year", F.lit(2018))
df_all_analysis = df_2016_analysis.unionByName(df_2017_analysis, allowMissingColumns=True) \
.unionByName(df_2018_analysis, allowMissingColumns=True)
print("Combined dataset row count:", df_all_analysis.count())
print("Combined dataset column count:", len(df_all_analysis.columns))
display(df_all_analysis.limit(10))
# COMMAND ----------
# MAGIC %md
# MAGIC Overall dataset summary
# COMMAND ----------
overall_summary = df_all_analysis.agg(
F.count("*").alias("total_flights"),
F.sum("cancelled").alias("total_cancelled_flights"),
F.sum("diverted").alias("total_diverted_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_departure_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arrival_delay"),
F.round(F.avg("distance"), 2).alias("avg_distance"),
F.round(F.avg("air_time"), 2).alias("avg_air_time")
)
display(overall_summary)
# COMMAND ----------
# MAGIC %md
# MAGIC Flight volume by year
# COMMAND ----------
flights_by_year = df_all_analysis.groupBy("dataset_year").agg(
F.count("*").alias("total_flights"),
F.sum("cancelled").alias("cancelled_flights"),
F.sum("diverted").alias("diverted_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate"),
F.round((F.sum("is_delayed") / F.count("*")) * 100, 2).alias("delay_rate")
).orderBy("dataset_year")
display(flights_by_year)
# COMMAND ----------
# MAGIC %md
# MAGIC Explicit filtering — delayed flights only
# COMMAND ----------
delayed_flights = df_all_analysis.filter(F.col("arr_delay") > 15)
print("Delayed flights count:", delayed_flights.count())
display(delayed_flights.limit(10))
print("Insight: Flights with arrival delay greater than 15 minutes are treated as delayed flights for further analysis.")
# COMMAND ----------
# MAGIC %md
# MAGIC Explicit filtering — cancelled flights only
# COMMAND ----------
cancelled_flights_only = df_all_analysis.filter(F.col("cancelled") == 1)
print("Cancelled flights count:", cancelled_flights_only.count())
display(cancelled_flights_only.limit(10))
print("Insight: This filtered subset isolates cancelled flights and helps identify which locations or time periods are associated with more cancellations.")
# COMMAND ----------
# MAGIC %md
# MAGIC Explicit filtering — long distance flights
# COMMAND ----------
long_distance_flights = df_all_analysis.filter(F.col("distance") >= 2000)
print("Long-distance flights count:", long_distance_flights.count())
display(long_distance_flights.limit(10))
print("Insight: Filtering long-distance flights helps compare whether longer routes experience different delay behaviour compared to shorter routes.")
# COMMAND ----------
# MAGIC %md
# MAGIC Busiest origin airports
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To identify airports with the highest traffic.
# COMMAND ----------
origin_flight_volume = df_all_analysis.groupBy("origin").agg(
F.count("*").alias("total_flights")
).orderBy(F.desc("total_flights"))
display(origin_flight_volume)
print("Insight: Airports with the highest flight counts represent the busiest origin hubs in the dataset.")
# COMMAND ----------
# MAGIC %md
# MAGIC Busiest destination airports
# COMMAND ----------
destination_flight_volume = df_all_analysis.groupBy("dest").agg(
F.count("*").alias("total_flights")
).orderBy(F.desc("total_flights"))
display(destination_flight_volume)
print("Insight: This analysis identifies the destination airports receiving the highest number of flights.")
# COMMAND ----------
# MAGIC %md
# MAGIC Origin airport delay analysis
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To identify airports with high average delays and cancellation rates.
# COMMAND ----------
origin_delay_analysis = df_all_analysis.groupBy("origin").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.sum("cancelled").alias("cancelled_flights"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate")
).orderBy(F.desc("total_flights"))
display(origin_delay_analysis)
# COMMAND ----------
# MAGIC %md
# MAGIC Destination airport delay analysis
# COMMAND ----------
destination_delay_analysis = df_all_analysis.groupBy("dest").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.sum("cancelled").alias("cancelled_flights"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate")
).orderBy(F.desc("avg_arr_delay"))
display(destination_delay_analysis)
print("Insight: This reveals destination airports where arriving flights experience the greatest average delay.")
# COMMAND ----------
# MAGIC %md
# MAGIC Busiest service hours
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC This directly matches the coursework example of identifying busiest service hours.
# COMMAND ----------
busiest_hours = df_all_analysis.groupBy("scheduled_dep_hour").agg(
F.count("*").alias("total_flights")
).orderBy(F.desc("total_flights"))
display(busiest_hours)
print("Insight: The hours with the highest flight counts represent the busiest service periods in airport operations.")
# COMMAND ----------
# MAGIC %md
# MAGIC Delay by service hour
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To find whether some times of the day experience more delays.
# COMMAND ----------
hourly_delay_analysis = df_all_analysis.groupBy("scheduled_dep_hour").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.sum("cancelled").alias("cancelled_flights"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate"),
F.round((F.sum("is_delayed") / F.count("*")) * 100, 2).alias("delay_rate")
).orderBy("scheduled_dep_hour")
display(hourly_delay_analysis)
print("Insight: This analysis shows how delay behaviour changes throughout the day and helps identify peak congestion hours.")
# COMMAND ----------
# MAGIC %md
# MAGIC Route analysis
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To identify frequently used and delay-prone routes.
# COMMAND ----------
route_analysis = df_all_analysis.groupBy("route").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.sum("cancelled").alias("cancelled_flights"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate")
).orderBy(F.desc("total_flights"))
display(route_analysis)
print("Insight: Route-level analysis helps identify both high-volume routes and routes with high average delay.")
# COMMAND ----------
# MAGIC %md
# MAGIC Worst routes by arrival delay
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To focus only on meaningful routes with sufficient flight count.
# COMMAND ----------
worst_routes_by_arr_delay = df_all_analysis.groupBy("route").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay")
).filter(
F.col("total_flights") >= 100
).orderBy(F.desc("avg_arr_delay"))
display(worst_routes_by_arr_delay.limit(20))
print("Insight: These routes have the highest average arrival delay among routes with significant traffic volume.")
# COMMAND ----------
# MAGIC %md
# MAGIC Monthly trend analysis
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To identify seasonal patterns and monthly operational trends.
# COMMAND ----------
monthly_analysis = df_all_analysis.groupBy("dataset_year", "month", "month_name").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.sum("cancelled").alias("cancelled_flights"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate"),
F.round((F.sum("is_delayed") / F.count("*")) * 100, 2).alias("delay_rate")
).orderBy("dataset_year", "month")
display(monthly_analysis)
print("Insight: Monthly analysis helps identify peak disruption periods and seasonal patterns in flight delays and cancellations.")
# COMMAND ----------
# MAGIC %md
# MAGIC Overall monthly pattern
# COMMAND ----------
overall_monthly_pattern = df_all_analysis.groupBy("month", "month_name").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate")
).orderBy("month")
display(overall_monthly_pattern)
print("Insight: This summarizes how delay and cancellation behaviour changes over the calendar year, regardless of specific year.")
# COMMAND ----------
# MAGIC %md
# MAGIC Day-of-week analysis
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To identify which days are operationally heavier or more delay-prone.
# COMMAND ----------
day_of_week_analysis = df_all_analysis.groupBy("day_of_week").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.sum("cancelled").alias("cancelled_flights"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate"),
F.round((F.sum("is_delayed") / F.count("*")) * 100, 2).alias("delay_rate")
).orderBy("day_of_week")
display(day_of_week_analysis)
print("Insight: This analysis helps determine whether certain weekdays are associated with higher delays or cancellations.")
# COMMAND ----------
# MAGIC %md
# MAGIC Delay category distribution
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To measure how flights are distributed across delay severity groups.
# COMMAND ----------
delay_category_distribution = df_all_analysis.groupBy("delay_category").agg(
F.count("*").alias("flight_count")
).orderBy(F.desc("flight_count"))
display(delay_category_distribution)
print("Insight: Most flights may fall into low-delay categories, while fewer flights experience severe delays.")
# COMMAND ----------
# MAGIC %md
# MAGIC Flight status distribution
# COMMAND ----------
flight_status_distribution = df_all_analysis.groupBy("flight_status").agg(
F.count("*").alias("flight_count")
).orderBy(F.desc("flight_count"))
display(flight_status_distribution)
print("Insight: This distinguishes operated flights from cancelled flights and provides a simple operational outcome summary.")
# COMMAND ----------
# MAGIC %md
# MAGIC Distance range analysis
# COMMAND ----------
df_distance_binned = df_all_analysis.withColumn(
"distance_range",
F.when(F.col("distance") < 500, "0-500")
.when((F.col("distance") >= 500) & (F.col("distance") < 1000), "500-1000")
.when((F.col("distance") >= 1000) & (F.col("distance") < 2000), "1000-2000")
.otherwise("2000+")
)
distance_delay_analysis = df_distance_binned.groupBy("distance_range").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate")
).orderBy("distance_range")
display(distance_delay_analysis)
print("Insight: Grouping distance into ranges makes it easier to understand how shorter and longer flights differ in delay behaviour.")
# COMMAND ----------
# MAGIC %md
# MAGIC Taxi time analysis
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To compare ground movement times across years.
# COMMAND ----------
taxi_time_analysis = df_all_analysis.groupBy("dataset_year").agg(
F.round(F.avg("taxi_out"), 2).alias("avg_taxi_out"),
F.round(F.avg("taxi_in"), 2).alias("avg_taxi_in")
).orderBy("dataset_year")
display(taxi_time_analysis)
print("Insight: Taxi-out and taxi-in times reflect airport surface congestion and ground handling efficiency.")
# COMMAND ----------
# MAGIC %md
# MAGIC Elapsed time analysis
# COMMAND ----------
elapsed_time_analysis = df_all_analysis.groupBy("dataset_year").agg(
F.round(F.avg("crs_elapsed_time"), 2).alias("avg_scheduled_elapsed_time"),
F.round(F.avg("actual_elapsed_time"), 2).alias("avg_actual_elapsed_time"),
F.round(F.avg("air_time"), 2).alias("avg_air_time")
).orderBy("dataset_year")
display(elapsed_time_analysis)
print("Insight: Comparing scheduled and actual elapsed time helps show whether flights consistently take longer than planned.")
# COMMAND ----------
# MAGIC %md
# MAGIC Year-wise origin airport analysis
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To compare airport-level performance across years.
# COMMAND ----------
origin_year_analysis = df_all_analysis.groupBy("dataset_year", "origin").agg(
F.count("*").alias("total_flights"),
F.round(F.avg("dep_delay"), 2).alias("avg_dep_delay"),
F.round(F.avg("arr_delay"), 2).alias("avg_arr_delay"),
F.round((F.sum("cancelled") / F.count("*")) * 100, 2).alias("cancellation_rate")
).filter(
F.col("total_flights") >= 100
).orderBy("dataset_year", F.desc("avg_arr_delay"))
display(origin_year_analysis)
print("Insight: This compares how airport performance changes year by year.")
# COMMAND ----------
# MAGIC %md
# MAGIC Ranking worst origin airports with window functions
# MAGIC
# MAGIC Purpose:
# MAGIC
# MAGIC To show advanced Spark usage and ranking logic.
# COMMAND ----------
origin_rank_window = Window.partitionBy("dataset_year").orderBy(F.desc("avg_arr_delay"))
worst_origin_ranked = origin_year_analysis.withColumn(
"delay_rank_within_year",
F.row_number().over(origin_rank_window)
)
display(worst_origin_ranked)
print("Insight: Window functions allow ranking of airports within each year based on average arrival delay.")
# COMMAND ----------
# MAGIC %md
# MAGIC Top 10 worst origin airports each year
# COMMAND ----------
top_10_worst_origins_each_year = worst_origin_ranked.filter(
F.col("delay_rank_within_year") <= 10
).orderBy("dataset_year", "delay_rank_within_year")
display(top_10_worst_origins_each_year)
print("Insight: These are the worst-performing origin airports in each year based on average arrival delay.")
# COMMAND ----------
# MAGIC %md
# MAGIC Best origin airports each year
# COMMAND ----------
best_origin_window = Window.partitionBy("dataset_year").orderBy(F.asc("avg_arr_delay"))
best_origin_ranked = origin_year_analysis.withColumn(
"best_rank_within_year",
F.row_number().over(best_origin_window)
)
top_10_best_origins_each_year = best_origin_ranked.filter(
F.col("best_rank_within_year") <= 10
).orderBy("dataset_year", "best_rank_within_year")
display(top_10_best_origins_each_year)
print("Insight: These are the best-performing origin airports in each year based on lowest average arrival delay.")
# COMMAND ----------
# MAGIC %md