-
Notifications
You must be signed in to change notification settings - Fork 2
/
spark_exercise_01.py
58 lines (35 loc) · 1.48 KB
/
spark_exercise_01.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
#!/usr/bin/env python
# coding: utf-8
# https://jaceklaskowski.github.io/spark-workshop/exercises/sql/split-function-with-variable-delimiter-per-row.html
# In[87]:
# Import PySpark
from pyspark.sql import SparkSession
#Create SparkSession
spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()
# In[88]:
# Data
records = [("50000.0#0#0#", "#"),("[email protected]@", "@"), ("1$", "$"), ("1000.00^Test_string", "^"),
("dog$cat^mouse", "^"), ("@[email protected]@", "@")]
# Columns
columns = ["VALUES", "separator"]
# Create a spark dataframe
df_records = spark.createDataFrame(records).toDF(*columns)
# In[89]:
from pyspark.sql import functions as F
# Using the string split
df_records.createOrReplaceTempView("strings")
result = spark.sql("""
select VALUES, separator,
length(values) as string_length,
(
CASE
WHEN separator not in ('$','^') THEN SPLIT(VALUES, separator)
WHEN separator = '$' THEN array(split_part(VALUES, "$", 1), "")
WHEN separator = '^' THEN array(split_part(VALUES, "^", 1), split_part(VALUES, "^", 2))
END
) AS VALUES_ARRAY
from strings;
""")
# In[90]:
extra = result.withColumn("VALUES_FILTERED", F.udf(lambda fname: [x for x in fname if x != ""])("VALUES_ARRAY"))
extra.show(truncate=False)