Pyspark - 基于RDD中的键的总和[重复]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

我有一个csv文件,如下所示:

ID,NAME,SUBJECT,MARKS
1,ABC,ECONOMICS,50
1,ABC,SCIENCE,60
1,ABC,ENGLISH,70
2,XYZ,ECONOMICS,50
2,XYZ,ENGLISH,40
2,XYZ,SCIENCE,65

我能够将它加载到Spark中的RDD

empRDD =  sc.textFile("/user/location/EMPmarksfile");
header = empRDD.first();
newEmpRDD = empRDD.filter(lambda x:x!=header);
PairEmpRDD = newEmpRDD.map(lambda x:(x.split(",")[0],x));

我试图使用RDD转换reduceByKeygroupByKey对每个学生的总分进行求和,并期望结果如下:

[1,ABC,180]
[2,XYZ,155]
apache-spark pyspark rdd
1个回答
1
投票

以下是使用dataframe api的方法

df =  spark.read.csv("/user/location/EMPmarksfile", header=True, inferSchema=True)
df.groupBy("ID","NAME").sum("MARKS").show(10,False)

我们也可以使用基于rdd的api

finalRdd = newEmpRDD.map(lambda x:(x.split(",")))\
    .map(lambda x: ((x[0],x[1]),int(x[3])))\
    .reduceByKey(lambda x,y:x+y)\
    .map(lambda x: (x[0][0],x[0][1],x[1]))
© www.soinside.com 2019 - 2024. All rights reserved.