-
Notifications
You must be signed in to change notification settings - Fork 0
/
2. Spark Cookbook.py
183 lines (144 loc) · 6.26 KB
/
2. Spark Cookbook.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
from pyspark.sql import SQLContext, Row
sqlContext = SQLContext(sc)
from pyspark.sql.types import StringType, IntegerType, StructType, StructField
from pyspark.sql.functions import udf
import datetime as datetime
import re as re
# SAMPLE DATA---------------------------------------------------------------
rdd1 = sc.parallelize([('X01',41,'US',3),
('X01',41,'UK',1),
('X01',41,'CA',2),
('X02',72,'US',4),
('X02',72,'UK',6),
('X02',72,'CA',7),
('X02',72,'XX',8)])
# convert to a Spark DataFrame
schema1 = StructType([StructField('ID', StringType(), True),
StructField('Age', IntegerType(), True),
StructField('Country', StringType(), True),
StructField('Score', IntegerType(), True)])
df1 = sqlContext.createDataFrame(rdd1, schema1)
rdd2 = sc.parallelize([('ID01',41,'MKTG',3),
('ID02',26,'MKTG',1),
('ID03',11,'MKTG',2),
('ID04',22,'OPS',4),
('ID05',30,'OPS',6),
('ID06',21,'IT',7),
('ID07',25,'IT',8)])
# convert to a Spark DataFrame
schema2 = StructType([StructField('ID', StringType(), True),
StructField('Age', IntegerType(), True),
StructField('Department', StringType(), True),
StructField('Tenure', IntegerType(), True)])
df2 = sqlContext.createDataFrame(rdd2, schema2)
rdd3 = sc.parallelize([('X01','2014-02-13T12:36:14.899','2014-02-13T12:31:56.876','sip:7806552624@10.94.2.11'),
('X02','2014-02-13T12:35:37.405','2014-02-13T12:32:13.321',''),
('X03','2014-02-13T12:36:03.825','2014-02-13T12:32:15.229','sip:6477746242@10.94.2.15'),
('XO4','missing','2014-02-13T12:32:36.881','sip:6046179264@10.94.2.11'),
('XO5','2014-02-13T12:36:52.721','2014-02-13T12:33:30.323','sip:4168777435@10.94.2.11')])
schema3 = StructType([StructField('ID', StringType(), True),
StructField('EndDateTime', StringType(), True),
StructField('StartDateTime', StringType(), True),
StructField('ANI', StringType(), True)])
df3 = sqlContext.createDataFrame(rdd3, schema3)
#######################################################################################
# USEFUL CODE SNIPPETS
#######################################################################################
IVRCallLogs.columns # show all column headers
IVRCallLogs.show(10) # show first ten rows of a dataframe
IVRCallLogs.take(10) # show first ten rows of an RDD
sqlContext.clearCache() # Removes all cached tables from the in-memory cache.
#######################################################################################
# DATA EXPLORATION TASKS
#######################################################################################
# Frequency Counts
df2.Department.distinct().count()
#######################################################################################
# DATA MUNGING TASKS
#######################################################################################
# DEALING WITH DUPLICATES--------------------------------------------------------------
# Select columns by which you want to remove duplicates
def get_key(x): return "{0}{1}{2}".format(x[0],x[2],x[3])
# create a new RDD to map the columns specified above as keys
m = df1.map(lambda x: (get_key(x),x))
# reduce by key to eliminate duplicates
r = m.reduceByKey(lambda x,y: (x))
# extract only the values of the key-values
r = r.values()
# Alternate approach with dataframe
myDF.groupBy("Name", "Country", "Score").agg("Name", max("Age"), "Country", "Score")
# RESHAPING DATA-------------------------------------------------------------------------
# A functional aproach
def reshape(t):
out = []
out.append(t[0])
out.append(t[1])
for v in brc.value:
if t[2] == v:
out.append(t[3])
else:
out.append(0)
return (out[0],out[1]),(out[2],out[3],out[4],out[5])
def cntryFilter(t):
if t[2] in brc.value:
return t
else:
pass
def addtup(t1,t2):
j=()
for k,v in enumerate(t1):
j=j+(t1[k]+t2[k],)
return j
def seq(tIntrm,tNext):
return addtup(tIntrm,tNext)
def comb(tP,tF):
return addtup(tP,tF)
countries = ['CA', 'UK', 'US', 'XX']
brc = sc.broadcast(countries)
reshaped = rdd1.filter(cntryFilter).map(reshape)
pivot = reshaped.aggregateByKey((0,0,0,0),seq,comb,1)
for i in pivot.collect():
print i
# The SQL/Hive approach:
df1.registerTempTable("table1")
query = '''
SELECT ID,
Age,
MAX(CASE WHEN Country='CA' THEN Score ELSE 0 END) AS CA,
MAX(CASE WHEN Country='UK' THEN Score ELSE 0 END) AS UK,
MAX(CASE WHEN Country='US' THEN Score ELSE 0 END) AS US,
MAX(CASE WHEN Country='XX' THEN Score ELSE NULL END) AS XX
FROM table1
GROUP BY ID, Age'''
res = sqlContext.sql(query)
res.show(5)
# Imputing categorical variables------------------------------------------------------------
def impute_region(x):
if x == 'CA' or x == 'US':
return 'North America'
elif x == 'UK':
return 'Europe'
impute_region = udf(impute_region, StringType())
df4 = df1.withColumn('Region', f(df1.Country))
# Dealing with Dates-------------------------------------------------------------------------
# Function to calculate time delta
def time_delta(y,x):
try:
end = datetime.strptime(y, '%Y-%m-%dT%H:%M:%S.%f')
start = datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f')
delta = (end-start).seconds
return delta
except:
return None
time_delta = udf(time_delta, IntegerType())
df5 = df3.withColumn('Duration', time_delta(df3.EndDateTime, df3.StartDateTime))
# Apply REGEX to columns--------------------------------------------------------------------
def ani(x):
try:
extract = re.search('(\d{10})', x, re.M|re.I)
out = extract.group(0)
return out
except:
return None
ani = udf(ani, StringType())
df6 = df3.withColumn('ANI', time_delta(df3.ANI))