如何在PySpark中执行groupBy?

2024-05-13 19:59:16 发布

您现在位置:Python中文网/ 问答频道 /正文

auto = sc.textFile("temp/auto_data.csv")
auto = auto.map(lambda x: x.split(","))
header = auto.first()
autoData = auto.filter(lambda a: a!=header)

现在我有了autoData中的数据

[[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']]

现在我想对第2个和第12个(最后一个)值执行groupBy()。怎么做?


Tags: thelambdaautokitheaderwheelktlck
1条回答
网友
1楼 · 发布于 2024-05-13 19:59:16

groupBy将生成键的函数作为参数,以便您可以执行以下操作:

autoData.groupBy(lambda row: (row[2], row[12]))

编辑

关于任务you've described in the commentsgroupBy只在组中收集数据,但不聚合数据。

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.map(lambda row: (row[2], int_or_zero(row[12])))
     .groupByKey()
     .mapValues(sum))

相关问题 更多 >