在PySpark中适当减少输入

时间:2015-02-05 01:22:49

标签: apache-spark apache-spark-sql

我正在尝试使用spark离散一些数据。

我的数据格式如下:

date           zip   amount
2013/04/02    04324  32.2
2013/04/01    23242  1.5
2013/04/02    99343  12

然后我有以下代码:

sampleTable = sqlCtx.inferSchema(columns)
sampleTable.registerAsTable("amounts")


exTable = sampleTable.map(lambda p: {"date":p.date,"zip":p.zip,"amount":p.amount}) 

然后我有一个离职的功能:

def discretize((key, data), cutoff=0.75):
    result = (data < np.percentile(index,cutoff))
    return result

我将获取此结果列,然后将其与原始数据集连接。

我正在尝试使用此声明执行操作:

exDiscretized = exTable.map(lambda x: (((dt.datetime.strptime(x.date,'%Y/%m/%d')).year, (dt.datetime.strptime(x.date,'%Y/%m/%d')).month), x.amount)).reduce(discretize).collect()
基本上,我想要一个((年,月),整行)的元组,这样我就可以找到每个月和每年组合的第75个百分点。

我能够让地图部分正常工作。当我拿出reduce部分时,我会让代码工作。

当我使用map和reduce运行语句时,我收到以下错误:

org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/opt/cloudera/parcels/CDH-5.2.0-1.cdh5.2.0.p0.36/lib/spark/python/pyspark/worker.py", line 79, in main
serializer.dump_stream(func(split_index, iterator), outfile)
  File "/opt/cloudera/parcels/CDH-5.2.0-1.cdh5.2.0.p0.36/lib/spark/python/pyspark/serializers.py", line 196, in dump_stream
self.serializer.dump_stream(self._batched(iterator), stream)
  File "/opt/cloudera/parcels/CDH-5.2.0-1.cdh5.2.0.p0.36/lib/spark/python/pyspark/serializers.py", line 127, in dump_stream
    for obj in iterator:
  File "/opt/cloudera/parcels/CDH-5.2.0-1.cdh5.2.0.p0.36/lib/spark/python/pyspark/serializers.py", line 185, in _batched
for item in iterator:
  File "/opt/cloudera/parcels/CDH-5.2.0-1.cdh5.2.0.p0.36/lib/spark/python/pyspark/rdd.py", line 715, in func
yield reduce(f, iterator, initial)
  File "<stdin>", line 2, in discretize
  File "/usr/local/lib/python2.7/dist-packages/numpy-1.9.1-py2.7-linux-x86_64.egg/numpy/lib/function_base.py", line 3051, in percentile
    q = array(q, dtype=np.float64, copy=True)
 ValueError: setting an array element with a sequence.

我不确定我做错了什么。也许它与我生成键值对的方式有关?

1 个答案:

答案 0 :(得分:1)

所以我认为问题的根源是reduce不会像你尝试使用它一样工作。由于您希望将单个键的所有数据组合在一起,因此函数groupByKey可能就是您要查找的那个。这是一个例子:

input = sc.parallelize([("hi", 1), ("bye", 0), ("hi", 3)])
groupedInput = input.groupByKey()
def top(x):
     data = list(x)
     percentile = np.percentile(data, 0.70)
     return filter(lambda x: x >= percentile , data) 
modifiedGroupedInput = groupedInput.mapValues(top)
modifiedGroupedInput.collect()

结果:

[('bye', [0]), ('hi', [3])]

一般来说,reduceByKey通常更好用,但既然你想同时考虑每个键的所有元素来计算