forked from cartershanklin/pyspark-cheatsheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cheatsheet.py
executable file
·4156 lines (3409 loc) · 133 KB
/
cheatsheet.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
#!/usr/bin/env python3
import argparse
import datetime
import inspect
import logging
import os
import pandas
import pyspark
import shutil
import sys
import yaml
from pyspark.sql import SparkSession, SQLContext
from slugify import slugify
from delta import *
warehouse_path = "file://{}/spark_warehouse".format(os.getcwd())
builder = (
SparkSession.builder.master("local[*]")
.config("spark.executor.memory", "2G")
.config("spark.driver.memory", "2G")
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
.config(
"spark.sql.catalog.spark_catalog",
"org.apache.spark.sql.delta.catalog.DeltaCatalog",
)
.config("spark.sql.warehouse.dir", warehouse_path)
.appName("cheatsheet")
)
spark = configure_spark_with_delta_pip(builder).getOrCreate()
sqlContext = SQLContext(spark)
def getShowString(df, n=10, truncate=True, vertical=False):
if isinstance(truncate, bool) and truncate:
return df._jdf.showString(n, 10, vertical)
else:
return df._jdf.showString(n, int(truncate), vertical)
def get_result_text(result, truncate=True):
if type(result) == tuple:
result_df, options = result
return getShowString(result_df, **options)
if type(result) == pyspark.sql.dataframe.DataFrame:
return getShowString(result, truncate=truncate)
elif type(result) == pandas.core.frame.DataFrame:
return str(result)
elif type(result) == list:
return "\n".join(result)
elif type(result) == dict and "image" in result:
return "![{}]({})".format(result["alt"], result["image"])
else:
return result
class snippet:
def __init__(self):
self.dataset = None
self.name = None
self.preconvert = False
self.skip_run = False
self.manual_output = None
self.truncate = True
def load_data(self):
assert self.dataset is not None, "Dataset not set"
if self.dataset == "UNUSED":
return None
if self.dataset == "covtype.parquet":
from pyspark.sql.functions import col
df = spark.read.format("parquet").load(
os.path.join("data", "covtype.parquet")
)
for column_name in df.columns:
df = df.withColumn(column_name, col(column_name).cast("int"))
return df
df = (
spark.read.format("csv")
.option("header", True)
.load(os.path.join("data", self.dataset))
)
if self.preconvert:
if self.dataset in ("auto-mpg.csv", "auto-mpg-fixed.csv"):
from pyspark.sql.functions import col
for (
column_name
) in (
"mpg cylinders displacement horsepower weight acceleration".split()
):
df = df.withColumn(column_name, col(column_name).cast("double"))
df = df.withColumn("modelyear", col("modelyear").cast("int"))
df = df.withColumn("origin", col("origin").cast("int"))
elif self.dataset == "customer_spend.csv":
from pyspark.sql.functions import col, to_date, udf
from pyspark.sql.types import DecimalType
from decimal import Decimal
from money_parser import price_str
money_convert = udf(
lambda x: Decimal(price_str(x)) if x is not None else None,
DecimalType(8, 4),
)
df = (
df.withColumn("customer_id", col("customer_id").cast("integer"))
.withColumn("spend_dollars", money_convert(df.spend_dollars))
.withColumn("date", to_date(df.date))
)
return df
def snippet(self, df):
assert False, "Snippet not overridden"
def run(self, show=True):
assert self.dataset is not None, "Dataset not set"
assert self.name is not None, "Name not set"
logging.info("--- {} ---".format(self.name))
if self.skip_run:
if self.manual_output:
result_text = self.manual_output
if show:
logging.info(result_text)
else:
return result_text
return None
self.df = self.load_data()
retval = self.snippet(self.df)
if show:
if retval is not None:
result_text = get_result_text(retval, self.truncate)
logging.info(result_text)
else:
return retval
class loadsave_dataframe_from_csv(snippet):
def __init__(self):
super().__init__()
self.name = "Load a DataFrame from CSV"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 100
def snippet(self, df):
# See https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/DataFrameReader.html
# for a list of supported options.
df = spark.read.format("csv").option("header", True).load("data/auto-mpg.csv")
return df
class loadsave_dataframe_from_csv_delimiter(snippet):
def __init__(self):
super().__init__()
self.name = "Load a DataFrame from a Tab Separated Value (TSV) file"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 110
def snippet(self, df):
# See https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/DataFrameReader.html
# for a list of supported options.
df = (
spark.read.format("csv")
.option("header", True)
.option("sep", "\t")
.load("data/auto-mpg.tsv")
)
return df
class loadsave_save_csv(snippet):
def __init__(self):
super().__init__()
self.name = "Save a DataFrame in CSV format"
self.category = "Accessing Data Sources"
self.dataset = "auto-mpg.csv"
self.priority = 120
def snippet(self, df):
# See https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/DataFrameWriter.html
# for a list of supported options.
df.write.csv("output.csv")
class loadsave_load_parquet(snippet):
def __init__(self):
super().__init__()
self.name = "Load a DataFrame from Parquet"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 200
def snippet(self, df):
df = (
spark.read.format("parquet").load("data/auto-mpg.parquet")
)
return df
class loadsave_save_parquet(snippet):
def __init__(self):
super().__init__()
self.name = "Save a DataFrame in Parquet format"
self.category = "Accessing Data Sources"
self.dataset = "auto-mpg.csv"
self.priority = 210
def snippet(self, df):
df.write.parquet("output.parquet")
class loadsave_read_jsonl(snippet):
def __init__(self):
super().__init__()
self.name = "Load a DataFrame from JSON Lines (jsonl) Formatted Data"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 300
def snippet(self, df):
# JSON Lines / jsonl format uses one JSON document per line.
# If you have data with mostly regular structure this is better than nesting it in an array.
# See https://jsonlines.org/
df = spark.read.json("data/weblog.jsonl")
return df
class loadsave_save_catalog(snippet):
def __init__(self):
super().__init__()
self.name = "Save a DataFrame into a Hive catalog table"
self.category = "Accessing Data Sources"
self.dataset = "auto-mpg.csv"
self.priority = 500
def snippet(self, df):
df.write.mode("overwrite").saveAsTable("autompg")
class loadsave_load_catalog(snippet):
def __init__(self):
super().__init__()
self.name = "Load a Hive catalog table into a DataFrame"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 510
def snippet(self, df):
# Load the table previously saved.
df = spark.table("autompg")
return df
class loadsave_read_from_s3(snippet):
def __init__(self):
super().__init__()
self.name = "Load a CSV file from Amazon S3"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 1000
self.skip_run = True
def snippet(self, df):
import configparser
config = configparser.ConfigParser()
config.read(os.path.expanduser("~/.aws/credentials"))
access_key = config.get("default", "aws_access_key_id")
secret_key = config.get("default", "aws_secret_access_key")
# Requires compatible hadoop-aws and aws-java-sdk-bundle JARs.
spark.conf.set("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider")
spark.conf.set("fs.s3a.access.key", access_key)
spark.conf.set("fs.s3a.secret.key", secret_key)
df = spark.read.format("csv").option("header", True).load("s3a://cheatsheet111/auto-mpg.csv")
return df
class loadsave_read_from_oci(snippet):
def __init__(self):
super().__init__()
self.name = "Load a CSV file from Oracle Cloud Infrastructure (OCI) Object Storage"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 1300
self.skip_run = True
def snippet(self, df):
import oci
oci_config = oci.config.from_file()
conf = spark.sparkContext.getConf()
conf.set("fs.oci.client.auth.tenantId", oci_config["tenancy"])
conf.set("fs.oci.client.auth.userId", oci_config["user"])
conf.set("fs.oci.client.auth.fingerprint", oci_config["fingerprint"])
conf.set("fs.oci.client.auth.pemfilepath", oci_config["key_file"])
conf.set(
"fs.oci.client.hostname",
"https://objectstorage.{0}.oraclecloud.com".format(oci_config["region"]),
)
PATH = "oci://<your_bucket>@<your_namespace/<your_path>"
df = spark.read.format("csv").option("header", True).load(PATH)
return df
class loadsave_read_oracle(snippet):
def __init__(self):
super().__init__()
self.name = "Read an Oracle DB table into a DataFrame using a Wallet"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 10000
self.skip_run = True
def snippet(self, df):
# Key variables you need.
# Get the tnsname from tnsnames.ora.
# Wallet path should point to an extracted wallet file.
password = "my_password"
table = "source_table"
tnsname = "my_tns_name"
user = "ADMIN"
wallet_path = "/path/to/your/wallet"
properties = {
"driver": "oracle.jdbc.driver.OracleDriver",
"oracle.net.tns_admin": tnsname,
"password": password,
"user": user,
}
url = f"jdbc:oracle:thin:@{tnsname}?TNS_ADMIN={wallet_path}"
df = spark.read.jdbc(url=url, table=table, properties=properties)
return df
class loadsave_write_oracle(snippet):
def __init__(self):
super().__init__()
self.name = "Write a DataFrame to an Oracle DB table using a Wallet"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 10100
self.skip_run = True
def snippet(self, df):
# Key variables you need.
# Get the tnsname from tnsnames.ora.
# Wallet path should point to an extracted wallet file.
password = "my_password"
table = "target_table"
tnsname = "my_tns_name"
user = "ADMIN"
wallet_path = "/path/to/your/wallet"
properties = {
"driver": "oracle.jdbc.driver.OracleDriver",
"oracle.net.tns_admin": tnsname,
"password": password,
"user": user,
}
url = f"jdbc:oracle:thin:@{tnsname}?TNS_ADMIN={wallet_path}"
# Possible modes are "Append", "Overwrite", "Ignore", "Error"
df.write.jdbc(url=url, table=table, mode="Append", properties=properties)
class loadsave_read_postgres(snippet):
def __init__(self):
super().__init__()
self.name = "Read a Postgres table into a DataFrame"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 11000
self.skip_run = True
def snippet(self, df):
# You need a compatible postgresql JDBC JAR.
pg_database = os.environ.get("PGDATABASE")
pg_host = os.environ.get("PGHOST")
pg_password = os.environ.get("PGPASSWORD")
pg_user = os.environ.get("PGUSER")
table = "test"
properties = {
"driver": "org.postgresql.Driver",
"user": pg_user,
"password": pg_password,
}
url = f"jdbc:postgresql://{pg_host}:5432/{pg_database}"
df = spark.read.jdbc(url=url, table=table, properties=properties)
return df
class loadsave_write_postgres(snippet):
def __init__(self):
super().__init__()
self.name = "Write a DataFrame to a Postgres table"
self.category = "Accessing Data Sources"
self.dataset = "auto-mpg.csv"
self.priority = 11100
self.skip_run = True
def snippet(self, df):
# You need a compatible postgresql JDBC JAR.
pg_database = os.environ.get("PGDATABASE")
pg_host = os.environ.get("PGHOST")
pg_password = os.environ.get("PGPASSWORD")
pg_user = os.environ.get("PGUSER")
table = "autompg"
properties = {
"driver": "org.postgresql.Driver",
"user": pg_user,
"password": pg_password,
}
url = f"jdbc:postgresql://{pg_host}:5432/{pg_database}"
df.write.jdbc(url=url, table=table, mode="Append", properties=properties)
class loadsave_dataframe_from_csv_provide_schema(snippet):
def __init__(self):
super().__init__()
self.name = "Provide the schema when loading a DataFrame from CSV"
self.category = "Data Handling Options"
self.dataset = "auto-mpg.csv"
self.priority = 100
def snippet(self, df):
# See https://spark.apache.org/docs/latest/api/python/_modules/pyspark/sql/types.html
# for a list of types.
from pyspark.sql.types import (
DoubleType,
IntegerType,
StringType,
StructField,
StructType,
)
schema = StructType(
[
StructField("mpg", DoubleType(), True),
StructField("cylinders", IntegerType(), True),
StructField("displacement", DoubleType(), True),
StructField("horsepower", DoubleType(), True),
StructField("weight", DoubleType(), True),
StructField("acceleration", DoubleType(), True),
StructField("modelyear", IntegerType(), True),
StructField("origin", IntegerType(), True),
StructField("carname", StringType(), True),
]
)
df = (
spark.read.format("csv")
.option("header", "true")
.schema(schema)
.load("data/auto-mpg.csv")
)
return df
class loadsave_overwrite_output_directory(snippet):
def __init__(self):
super().__init__()
self.name = "Save a DataFrame to CSV, overwriting existing data"
self.category = "Data Handling Options"
self.dataset = "auto-mpg.csv"
self.priority = 200
def snippet(self, df):
df.write.mode("overwrite").csv("output.csv")
class loadsave_csv_with_header(snippet):
def __init__(self):
super().__init__()
self.name = "Save a DataFrame to CSV with a header"
self.category = "Data Handling Options"
self.dataset = "auto-mpg.csv"
self.priority = 300
def snippet(self, df):
# See https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/DataFrameWriter.html
# for a list of supported options.
df.coalesce(1).write.csv("header.csv", header="true")
class loadsave_single_output_file(snippet):
def __init__(self):
super().__init__()
self.name = "Save a DataFrame in a single CSV file"
self.category = "Data Handling Options"
self.dataset = "auto-mpg.csv"
self.priority = 400
def snippet(self, df):
df.coalesce(1).write.csv("single.csv")
class loadsave_dynamic_partitioning(snippet):
def __init__(self):
super().__init__()
self.name = "Save DataFrame as a dynamic partitioned table"
self.category = "Data Handling Options"
self.dataset = "auto-mpg.csv"
self.priority = 500
def snippet(self, df):
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
df.write.mode("append").partitionBy("modelyear").saveAsTable("autompg_partitioned")
class loadsave_overwrite_specific_partitions(snippet):
def __init__(self):
super().__init__()
self.name = "Overwrite specific partitions"
self.category = "Data Handling Options"
self.dataset = "auto-mpg.csv"
self.priority = 501
self.skip_run = True
def snippet(self, df):
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
your_dataframe.write.mode("overwrite").insertInto("your_table")
class loadsave_money(snippet):
def __init__(self):
super().__init__()
self.name = "Load a CSV file with a money column into a DataFrame"
self.category = "Data Handling Options"
self.dataset = "UNUSED"
self.priority = 600
def snippet(self, df):
from pyspark.sql.functions import udf
from pyspark.sql.types import DecimalType
from decimal import Decimal
# Load the text file.
df = (
spark.read.format("csv")
.option("header", True)
.load("data/customer_spend.csv")
)
# Convert with a hardcoded custom UDF.
money_udf = udf(lambda x: Decimal(x[1:].replace(",", "")), DecimalType(8, 4))
money1 = df.withColumn("spend_dollars", money_udf(df.spend_dollars))
# Convert with the money_parser library (much safer).
from money_parser import price_str
money_convert = udf(
lambda x: Decimal(price_str(x)) if x is not None else None,
DecimalType(8, 4),
)
money2 = df.withColumn("spend_dollars", money_convert(df.spend_dollars))
return money2
class dfo_modify_column(snippet):
def __init__(self):
super().__init__()
self.name = "Modify a DataFrame column"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 200
def snippet(self, df):
from pyspark.sql.functions import col, concat, lit
df = df.withColumn("modelyear", concat(lit("19"), col("modelyear")))
return df
class dfo_add_column_builtin(snippet):
def __init__(self):
super().__init__()
self.name = "Add a new column to a DataFrame"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 100
def snippet(self, df):
from pyspark.sql.functions import upper, lower
df = df.withColumn("upper", upper(df.carname)).withColumn(
"lower", lower(df.carname)
)
return df
class dfo_add_column_custom_udf(snippet):
def __init__(self):
super().__init__()
self.name = "Create a custom UDF"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 2100
def snippet(self, df):
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
first_word_udf = udf(lambda x: x.split()[0], StringType())
df = df.withColumn("manufacturer", first_word_udf(df.carname))
return df
class dfo_concat_columns(snippet):
def __init__(self):
super().__init__()
self.name = "Concatenate columns"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 450
def snippet(self, df):
from pyspark.sql.functions import concat, col, lit
df = df.withColumn(
"concatenated", concat(col("cylinders"), lit("_"), col("mpg"))
)
return df
class dfo_string_to_double(snippet):
def __init__(self):
super().__init__()
self.name = "Convert String to Double"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1000
def snippet(self, df):
from pyspark.sql.functions import col
df = df.withColumn("horsepower", col("horsepower").cast("double"))
return df
class dfo_string_to_integer(snippet):
def __init__(self):
super().__init__()
self.name = "Convert String to Integer"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1100
def snippet(self, df):
from pyspark.sql.functions import col
df = df.withColumn("horsepower", col("horsepower").cast("int"))
return df
class dfo_change_column_name_single(snippet):
def __init__(self):
super().__init__()
self.name = "Change a column name"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 600
def snippet(self, df):
df = df.withColumnRenamed("horsepower", "horses")
return df
class dfo_change_column_name_multi(snippet):
def __init__(self):
super().__init__()
self.name = "Change multiple column names"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 700
def snippet(self, df):
df = df.withColumnRenamed("horsepower", "horses").withColumnRenamed(
"modelyear", "year"
)
return df
class dfo_column_to_python_list(snippet):
def __init__(self):
super().__init__()
self.name = "Convert a DataFrame column to a Python list"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 710
def snippet(self, df):
names = df.select("carname").rdd.flatMap(lambda x: x).collect()
return str(names[:10])
class dfo_consume_as_dict(snippet):
def __init__(self):
super().__init__()
self.name = "Consume a DataFrame row-wise as Python dictionaries"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.preconvert = True
self.priority = 730
def snippet(self, df):
first_three = df.limit(3)
for row in first_three.collect():
my_dict = row.asDict()
# EXCLUDE
return """
{'mpg': '18.0', 'cylinders': '8', 'displacement': '307.0', 'horsepower': '130.0', 'weight': '3504.', 'acceleration': '12.0', 'modelyear': '70', 'origin': '1', 'carname': 'chevrolet chevelle malibu'}
{'mpg': '15.0', 'cylinders': '8', 'displacement': '350.0', 'horsepower': '165.0', 'weight': '3693.', 'acceleration': '11.5', 'modelyear': '70', 'origin': '1', 'carname': 'buick skylark 320'}
{'mpg': '18.0', 'cylinders': '8', 'displacement': '318.0', 'horsepower': '150.0', 'weight': '3436.', 'acceleration': '11.0', 'modelyear': '70', 'origin': '1', 'carname': 'plymouth satellite'}
"""
# INCLUDE
class dfo_scalar_query_to_python_variable(snippet):
def __init__(self):
super().__init__()
self.name = "Convert a scalar query to a Python value"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 720
def snippet(self, df):
average = df.agg(dict(mpg="avg")).first()[0]
print(average)
return str(average)
class dfo_dataframe_from_rdd(snippet):
def __init__(self):
super().__init__()
self.name = "Convert an RDD to Data Frame"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1500
def load_data(self):
return spark.sparkContext.textFile(os.path.join("data", self.dataset))
def snippet(self, rdd):
from pyspark.sql import Row
row = Row("val")
df = rdd.map(row).toDF()
return df
class dfo_empty_dataframe(snippet):
def __init__(self):
super().__init__()
self.name = "Create an empty dataframe with a specified schema"
self.category = "DataFrame Operations"
self.dataset = "NA"
self.priority = 900
def load_data(self):
pass
def snippet(self, rdd):
from pyspark.sql.types import StructField, StructType, LongType, StringType
schema = StructType(
[
StructField("my_id", LongType(), True),
StructField("my_string", StringType(), True),
]
)
df = spark.createDataFrame([], schema)
return df
class dfo_drop_column(snippet):
def __init__(self):
super().__init__()
self.name = "Drop a column"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 500
def snippet(self, df):
df = df.drop("horsepower")
return df
class dfo_print_contents_rdd(snippet):
def __init__(self):
super().__init__()
self.name = "Print the contents of an RDD"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1600
def load_data(self):
return spark.sparkContext.textFile(os.path.join("data", self.dataset))
def snippet(self, rdd):
print(rdd.take(10))
return str(rdd.take(10))
class dfo_print_contents_dataframe(snippet):
def __init__(self):
super().__init__()
self.name = "Print the contents of a DataFrame"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1700
def snippet(self, df):
df.show(10)
return df
class dfo_column_conditional(snippet):
def __init__(self):
super().__init__()
self.name = "Add a column with multiple conditions"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 300
def snippet(self, df):
from pyspark.sql.functions import col, when
df = df.withColumn(
"mpg_class",
when(col("mpg") <= 20, "low")
.when(col("mpg") <= 30, "mid")
.when(col("mpg") <= 40, "high")
.otherwise("very high"),
)
return df
class dfo_constant_column(snippet):
def __init__(self):
super().__init__()
self.name = "Add a constant column"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 400
def snippet(self, df):
from pyspark.sql.functions import lit
df = df.withColumn("one", lit(1))
return df
class dfo_foreach(snippet):
def __init__(self):
super().__init__()
self.name = "Process each row of a DataFrame"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1800
def snippet(self, df):
import os
def foreach_function(row):
if row.horsepower is not None:
os.system("echo " + row.horsepower)
df.foreach(foreach_function)
class dfo_map(snippet):
def __init__(self):
super().__init__()
self.name = "DataFrame Map example"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1900
def snippet(self, df):
def map_function(row):
if row.horsepower is not None:
return [float(row.horsepower) * 10]
else:
return [None]
df = df.rdd.map(map_function).toDF()
return df
class dfo_flatmap(snippet):
def __init__(self):
super().__init__()
self.name = "DataFrame Flatmap example"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 2000
def snippet(self, df):
from pyspark.sql.types import Row
def flatmap_function(row):
if row.cylinders is not None:
return list(range(int(row.cylinders)))
else:
return [None]
rdd = df.rdd.flatMap(flatmap_function)
row = Row("val")
df = rdd.map(row).toDF()
return df
class dfo_constant_dataframe(snippet):
def __init__(self):
super().__init__()
self.name = "Create a constant dataframe"
self.category = "DataFrame Operations"
self.dataset = "UNUSED"
self.priority = 950
def snippet(self, df):
import datetime
from pyspark.sql.types import (
StructField,
StructType,
LongType,
StringType,
TimestampType,
)
schema = StructType(
[
StructField("my_id", LongType(), True),
StructField("my_string", StringType(), True),
StructField("my_timestamp", TimestampType(), True),
]
)
df = spark.createDataFrame(
[
(1, "foo", datetime.datetime.strptime("2021-01-01", "%Y-%m-%d")),
(2, "bar", datetime.datetime.strptime("2021-01-02", "%Y-%m-%d")),
],
schema,
)
return df
class dfo_select_particular(snippet):
def __init__(self):
super().__init__()
self.name = "Select particular columns from a DataFrame"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 800
def snippet(self, df):
df = df.select(["mpg", "cylinders", "displacement"])
return df
class dfo_size(snippet):
def __init__(self):
super().__init__()
self.name = "Get the size of a DataFrame"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1200
def snippet(self, df):
print("{} rows".format(df.count()))
print("{} columns".format(len(df.columns)))
# EXCLUDE
return [
"{} rows".format(df.count()),
"{} columns".format(len(df.columns)),
]
# INCLUDE
class dfo_get_number_partitions(snippet):
def __init__(self):
super().__init__()
self.name = "Get a DataFrame's number of partitions"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 1300
def snippet(self, df):
print("{} partition(s)".format(df.rdd.getNumPartitions()))
return "{} partition(s)".format(df.rdd.getNumPartitions())
class dfo_get_dtypes(snippet):
def __init__(self):
super().__init__()
self.name = "Get data types of a DataFrame's columns"
self.category = "DataFrame Operations"