Pyspark:groupby然后计算真值

Ana*_*sia 3 apache-spark pyspark

我的数据结构是JSON格式:

"header"{"studentId":"1234","time":"2016-06-23","homeworkSubmitted":True}
"header"{"studentId":"1234","time":"2016-06-24","homeworkSubmitted":True}
"header"{"studentId":"1234","time":"2016-06-25","homeworkSubmitted":True}
"header"{"studentId":"1236","time":"2016-06-23","homeworkSubmitted":False}
"header"{"studentId":"1236","time":"2016-06-24","homeworkSubmitted":True}
....
Run Code Online (Sandbox Code Playgroud)

我需要绘制一个直方图,显示家庭作业的数量已提交:对所有stidentId为真.我编写的代码使数据结构变得扁平化,因此我的密钥是header.studentId,header.time和header.homeworkSubmitted.

我使用keyBy按studentId分组:

    initialRDD.keyBy(lambda row: row['header.studentId'])
              .map(lambda (k,v): (k,v['header.homeworkSubmitted']))
              .map(mapTF).groupByKey().mapValues(lambda x: Counter(x)).collect()
Run Code Online (Sandbox Code Playgroud)

这给了我这样的结果:

("1234", Counter({0:0, 1:3}),
("1236", Counter(0:1, 1:1))
Run Code Online (Sandbox Code Playgroud)

我只需要计数1,可能映射到列表,以便我可以使用matplotlib绘制直方图.我不知道如何继续并过滤所有内容.

编辑:最后我遍历字典并将计数添加到列表中,然后绘制列表的直方图.我想知道是否有一种更优雅的方式来完成我在代码中概述的整个过程.

Shu*_*uan 10

df = sqlContext.read.json('/path/to/your/dataset/')
df.filter(df.homeworkSubmitted == True).groupby(df.studentId).count()
Run Code Online (Sandbox Code Playgroud)

请注意,如果存在"header"True代替,则它不是有效的JSONtrue