-
Notifications
You must be signed in to change notification settings - Fork 217
/
Copy pathcheatsheet.py
executable file
·5367 lines (4441 loc) · 195 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.driver.memory", "2G")
.config("spark.executor.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, extra_packages=["org.postgresql:postgresql:42.4.0"]
).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
self.requires_environment = False
self.docmd = None
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
self.docmd = """
See https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/DataFrameReader.html for a list of supported options.
"""
def snippet(self, df):
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
self.docmd = """
See https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/DataFrameReader.html for a list of supported options.
"""
def snippet(self, df):
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
self.docmd = """
See https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/DataFrameWriter.html for a list of supported options.
"""
def snippet(self, auto_df):
auto_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
self.documd = """
Using the parquet format loads parquet files. If the path is a directory, all files in the directory will be combined into one DataFrame. Loading Parquet files does not require the schema to be given.
"""
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, auto_df):
auto_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
self.docmd = """
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 [jsonlines.org](https://jsonlines.org/)
"""
def snippet(self, df):
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
self.docmd = """
Save a DataFrame to a Hive-compatible catalog. Use `table` to save in the session's current database or `database.table` to save
in a specific database.
"""
def snippet(self, auto_df):
auto_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
self.docmd = """Load a DataFrame from a particular table. Use `table` to load from the session's current database or `database.table` to load from a specific database.
"""
def snippet(self, df):
df = spark.table("autompg")
return df
class loadsave_load_sql(snippet):
def __init__(self):
super().__init__()
self.name = "Load a DataFrame from a SQL query"
self.category = "Accessing Data Sources"
self.dataset = "UNUSED"
self.priority = 520
self.docmd = """
This example shows loading a DataFrame from a query run over the a table in a Hive-compatible catalog.
"""
def snippet(self, df):
df = sqlContext.sql(
"select carname, mpg, horsepower from autompg where horsepower > 100 and mpg > 25"
)
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
self.docmd = """
This example shows how to load a CSV file from AWS S3. This example uses a credential pair and the `SimpleAWSCredentialsProvider`. For other authentication options, refer to the [Hadoop-AWS module documentation](https://hadoop.apache.org/docs/stable/hadoop-aws/tools/hadoop-aws/index.html).
"""
def snippet(self, df):
import configparser
import os
config = configparser.ConfigParser()
config.read(os.path.expanduser("~/.aws/credentials"))
access_key = config.get("default", "aws_access_key_id").replace('"', "")
secret_key = config.get("default", "aws_secret_access_key").replace('"', "")
# 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
self.docmd = """
This example shows loading data from Oracle Cloud Infrastructure Object Storage using an API key.
"""
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
self.docmd = """
Get the tnsname from tnsnames.ora. The wallet path should point to an extracted wallet file. The wallet files need to be available on all nodes.
"""
def snippet(self, df):
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
self.docmd = """
Get the tnsname from tnsnames.ora. The wallet path should point to an extracted wallet file. The wallet files need to be available on all nodes.
"""
def snippet(self, df):
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_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 = 11000
self.requires_environment = True
self.docmd = """
You need a Postgres JDBC driver to connect to a Postgres database.
Options include:
- Add `org.postgresql:postgresql:<version>` to `spark.jars.packages`
- Provide the JDBC driver using `spark-submit --jars`
- Add the JDBC driver to your Spark runtime (not recommended)
If you use Delta Lake there is a special procedure for specifying `spark.jars.packages`, see the source code that generates this file for details.
"""
def snippet(self, auto_df):
pg_database = os.environ.get("PGDATABASE") or "postgres"
pg_host = os.environ.get("PGHOST") or "localhost"
pg_password = os.environ.get("PGPASSWORD") or "password"
pg_user = os.environ.get("PGUSER") or "postgres"
table = "autompg"
properties = {
"driver": "org.postgresql.Driver",
"user": pg_user,
"password": pg_password,
}
url = f"jdbc:postgresql://{pg_host}:5432/{pg_database}"
auto_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 = 11010
self.requires_environment = True
self.docmd = """
You need a Postgres JDBC driver to connect to a Postgres database.
Options include:
- Add `org.postgresql:postgresql:<version>` to `spark.jars.packages`
- Provide the JDBC driver using `spark-submit --jars`
- Add the JDBC driver to your Spark runtime (not recommended)
"""
def snippet(self, df):
pg_database = os.environ.get("PGDATABASE") or "postgres"
pg_host = os.environ.get("PGHOST") or "localhost"
pg_password = os.environ.get("PGPASSWORD") or "password"
pg_user = os.environ.get("PGUSER") or "postgres"
table = "autompg"
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_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 = "UNUSED"
self.priority = 100
self.docmd = """
See https://spark.apache.org/docs/latest/api/python/_modules/pyspark/sql/types.html for a list of types.
"""
def snippet(self, df):
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, auto_df):
auto_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
self.docmd = """
See https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/DataFrameWriter.html for a list of supported options.
"""
def snippet(self, auto_df):
auto_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
self.docmd = """
This example outputs CSV data to a single file. The file will be written in a directory called single.csv and have a random name. There is no way to change this behavior.
If you need to write to a single file with a name you choose, consider converting it to a Pandas dataframe and saving it using Pandas.
Either way all data will be collected on one node before being written so be careful not to run out of memory.
"""
def snippet(self, auto_df):
auto_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
self.docmd = """
When you write using dynamic partitioning, the output partitions are determined bby the values of a column rather than specified in code.
The values of the partitions will appear as subdirectories and are not contained in the output files, i.e. they become "virtual columns". When you read a partition table these virtual columns will be part of the DataFrame.
Dynamic partitioning has the potential to create many small files, this will impact performance negatively. Be sure the partition columns do not have too many distinct values and limit the use of multiple virtual columns.
"""
def snippet(self, auto_df):
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
auto_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
self.docmd = """
Enabling dynamic partitioning lets you add or overwrite partitions based on DataFrame contents. Without dynamic partitioning the overwrite will overwrite the entire table.
With dynamic partitioning, partitions with keys in the DataFrame are overwritten, but partitions not in the DataFrame are untouched.
"""
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
self.docmd = """
Spark is not that smart when it comes to parsing numbers, not allowing things like commas. If you need to load monetary amounts the safest option is to use a parsing library like `money_parser`.
"""
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),
)
df = df.withColumn("spend_dollars", money_convert(df.spend_dollars))
return df
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
self.docmd = """
Modify a column in-place using `withColumn`, specifying the output column name to be the same as the existing column name.
"""
def snippet(self, auto_df):
from pyspark.sql.functions import col, concat, lit
df = auto_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
self.docmd = """
`withColumn` returns a new DataFrame with a column added to the source DataFrame. `withColumn` can be chained together multiple times.
"""
def snippet(self, auto_df):
from pyspark.sql.functions import upper, lower
df = auto_df.withColumn("upper", upper(auto_df.carname)).withColumn(
"lower", lower(auto_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
self.docmd = """
Create a UDF by providing a function to the udf function. This example shows a [lambda function](https://docs.python.org/3/reference/expressions.html#lambdas-1). You can also use ordinary functions for more complex UDFs.
"""
def snippet(self, auto_df):
from pyspark.sql.functions import col, udf
from pyspark.sql.types import StringType
first_word_udf = udf(lambda x: x.split()[0], StringType())
df = auto_df.withColumn("manufacturer", first_word_udf(col("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
self.docmd = """TODO"""
def snippet(self, auto_df):
from pyspark.sql.functions import concat, col, lit
df = auto_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, auto_df):
from pyspark.sql.functions import col
df = auto_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, auto_df):
from pyspark.sql.functions import col
df = auto_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, auto_df):
df = auto_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
self.docmd = """
If you need to change multiple column names you can chain `withColumnRenamed` calls together. If you want to change all column names see "Change all column names at once".
"""
def snippet(self, auto_df):
df = auto_df.withColumnRenamed("horsepower", "horses").withColumnRenamed(
"modelyear", "year"
)
return df
class dfo_change_column_name_all(snippet):
def __init__(self):
super().__init__()
self.name = "Change all column names at once"
self.category = "DataFrame Operations"
self.dataset = "auto-mpg.csv"
self.priority = 710
self.docmd = """
To rename all columns use toDF with the desired column names in the argument list. This example puts an X in front of all column names.
"""
def snippet(self, auto_df):
df = auto_df.toDF(*["X" + name for name in auto_df.columns])
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
self.docmd = """
Steps below:
- `select` the target column, this example uses `carname`.
- Access the DataFrame's rdd using `.rdd`
- Use `flatMap` to convert the rdd's `Row` objects into simple values.
- Use `collect` to assemble everything into a list.
"""
def snippet(self, auto_df):
names = auto_df.select("carname").rdd.flatMap(lambda x: x).collect()
print(str(names[:10]))
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
self.docmd = """
Steps below:
- `collect` all DataFrame Rows in the driver.
- Iterate over the Rows.
- Call the Row's `asDict` method to convert the Row to a Python dictionary.
"""
def snippet(self, auto_df):
first_three = auto_df.limit(3)
for row in first_three.collect():
my_dict = row.asDict()
print(my_dict)
# 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
self.docmd = """
If you have a `DataFrame` with one row and one column, how do you access its value?
Steps below:
- Create a DataFrame with one row and one column, this example uses an average but it could be anything.
- Call the DataFrame's `first` method, this returns the first `Row` of the DataFrame.
- `Row`s can be accessed like arrays, so we extract the zeroth value of the first `Row` using `first()[0]`.
"""
def snippet(self, auto_df):
average = auto_df.agg(dict(mpg="avg")).first()[0]
print(str(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.preconvert = True
self.priority = 1500
self.docmd = """
If you have an `rdd` how do you convert it to a `DataFrame`? The `rdd` method `toDf` can be used, but the `rdd` must be a collection of `Row` objects.
Steps below:
- Create an `rdd` to be converted to a `DataFrame`.
- Use the `rdd`'s `map` method:
- The example uses a lambda function to convert `rdd` elements to `Row`s.
- The `Row` constructor request key/value pairs with the key serving as the "column name".
- Each `rdd` entry is converted to a dictionary and the dictionary is unpacked to create the `Row`.
- `map` creates a new `rdd` containing all the `Row` objects.
- This new `rdd` is converted to a `DataFrame` using the `toDF` method.
The second example is a variation on the first, modifying source `rdd` entries while creating the target `rdd`.
"""
def snippet(self, auto_df):
from pyspark.sql import Row
# First, get the RDD from the DataFrame.
rdd = auto_df.rdd
# This converts it back to an RDD with no changes.
df = rdd.map(lambda x: Row(**x.asDict())).toDF()
# This changes the rows before creating the DataFrame.
df = rdd.map(
lambda x: Row(**{k: v * 2 for (k, v) in x.asDict().items()})
).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
self.docmd = """
You can create an empty `DataFrame` the same way you create other in-line `DataFrame`s, but using an empty list.
"""
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, auto_df):
df = auto_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
self.docmd = """
To see an `RDD`'s contents, convert the output of the `take` method to a string.
"""
def snippet(self, auto_df):
rdd = auto_df.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, auto_df):
auto_df.show(10)
return auto_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
self.docmd = """
To set a new column's values when using `withColumn`, use the `when` / `otherwise` idiom. Multiple `when` conditions can be chained together.
"""