forked from databricks/learning-spark
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerKeyAvg.py
More file actions
30 lines (24 loc) · 817 Bytes
/
Copy pathPerKeyAvg.py
File metadata and controls
30 lines (24 loc) · 817 Bytes
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
"""
>>> from pyspark.context import SparkContext
>>> sc = SparkContext('local', 'test')
>>> input = [("coffee", 1), ("pandas", 2), ("coffee", 3), ("very", 4)]
>>> b = sc.parallelize(input)
>>> perKeyAvg(b)
"""
import sys
from pyspark import SparkContext
def perKeyAvg(nums):
"""Compute the avg"""
sumCount = nums.combineByKey((lambda x: (x, 1)),
(lambda x, y: (x[0] + y, x[1] + 1)),
(lambda x, y: (x[0] + y[0], x[1] + y[1])))
return sumCount.collectAsMap()
if __name__ == "__main__":
master = "local"
if len(sys.argv) == 2:
master = sys.argv[1]
sc = SparkContext(master, "Sum")
nums = sc.parallelize(
[("coffee", 1), ("pandas", 2), ("coffee", 3), ("very", 4)])
avg = perKeyAvg(nums)
print avg