Python 如何在PySpark中执行groupBy?
现在我有了autoData中的数据Python 如何在PySpark中执行groupBy?,python,apache-spark,pyspark,Python,Apache Spark,Pyspark,现在我有了autoData中的数据 auto = sc.textFile("temp/auto_data.csv") auto = auto.map(lambda x: x.split(",")) header = auto.first() autoData = auto.filter(lambda a: a!=header) 现在我想对第2个和第12个(最后一个)值执行groupBy()。如何做到这一点 groupBy将生成键的函数作为参数,以便您可以执行以下操作: [[u'', u'ETZ
auto = sc.textFile("temp/auto_data.csv")
auto = auto.map(lambda x: x.split(","))
header = auto.first()
autoData = auto.filter(lambda a: a!=header)
现在我想对第2个和第12个(最后一个)值执行
groupBy()。如何做到这一点 groupBy
将生成键的函数作为参数,以便您可以执行以下操作:
[[u'', u'ETZ', u'AS1', u'CUT000021', u'THE TU-WHEEL SPARES', u'DIBRUGARH', u'201505', u'LCK ', u'2WH ', u'KIT', u'KT-2069CZ', u'18', u'8484'], [u'', u'ETZ', u'AS1', u'CUT000021', u'THE TU-WHEEL SPARES', u'DIBRUGARH', u'201505', u'LCK ', u'2WH ', u'KIT', u'KT-2069SZ', u'9', u'5211']]
from operator import add
def int_or_zero(s):
try:
return int(s)
except ValueError:
return 0
autoData.map(lambda row: (row[2], int_or_zero(row[12]))).reduceByKey(add)
编辑:
关于任务groupBy
只在组中收集数据,但不聚合数据
autoData.groupBy(lambda row: (row[2], row[12]))
使用groupBy
的低效版本可能如下所示:
[[u'', u'ETZ', u'AS1', u'CUT000021', u'THE TU-WHEEL SPARES', u'DIBRUGARH', u'201505', u'LCK ', u'2WH ', u'KIT', u'KT-2069CZ', u'18', u'8484'], [u'', u'ETZ', u'AS1', u'CUT000021', u'THE TU-WHEEL SPARES', u'DIBRUGARH', u'201505', u'LCK ', u'2WH ', u'KIT', u'KT-2069SZ', u'9', u'5211']]
from operator import add
def int_or_zero(s):
try:
return int(s)
except ValueError:
return 0
autoData.map(lambda row: (row[2], int_or_zero(row[12]))).reduceByKey(add)
如果我使用autoData.groupBy(lambda行:(行[2],int(行[12])),现在第二个值是int,但它给出的结果与前面相同。我想使用groupBy()按秒计算最后一列的和。我已经使用map reduce将此结果存档。但是我想用这个函数。