forked from databricks/learning-spark
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAvgMapPartitions.py
More file actions
39 lines (30 loc) · 829 Bytes
/
Copy pathAvgMapPartitions.py
File metadata and controls
39 lines (30 loc) · 829 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
31
32
33
34
35
36
37
38
39
"""
>>> from pyspark.context import SparkContext
>>> sc = SparkContext('local', 'test')
>>> b = sc.parallelize([1, 2, 3, 4])
>>> avg(b)
2.5
"""
import sys
from pyspark import SparkContext
def partitionCtr(nums):
"""Compute sumCounter for partition"""
sumCount = [0, 0]
for num in nums:
sumCount[0] += num
sumCount[1] += 1
return [sumCount]
def combineCtrs(c1, c2):
return (c1[0] + c2[0], c1[1] + c2[1])
def basicAvg(nums):
"""Compute the avg"""
sumCount = nums.mapPartitions(partitionCtr).reduce(combineCtrs)
return sumCount[0] / float(sumCount[1])
if __name__ == "__main__":
cluster = "local"
if len(sys.argv) == 2:
cluster = sys.argv[1]
sc = SparkContext(cluster, "Sum")
nums = sc.parallelize([1, 2, 3, 4])
avg = basicAvg(nums)
print avg