我有以下两个第一行的数据框:
['station_id', 'country', 'temperature', 'time']
['12', 'usa', '22', '12:04:14']
我希望按照“法国”中前100个电台的降序显示平均温度。
在pyspark中执行此操作的最佳方式(效率最高)是什么?
答案 0 :(得分:9)
我们通过以下方式将您的查询翻译为Spark SQL
:
from pyspark.sql.functions import mean, desc
df.filter(df["country"] == "france") \ # only french stations
.groupBy("station_id") \ # by station
.agg(mean("temperature").alias("average_temp")) \ # calculate average
.orderBy(desc("average_temp")) \ # order by average
.take(100) # return first 100 rows
使用RDD
API和匿名函数:
df.rdd \
.filter(lambda x: x[1] == "france") \ # only french stations
.map(lambda x: (x[0], x[2])) \ # select station & temp
.mapValues(lambda x: (x, 1)) \ # generate count
.reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1])) \ # calculate sum & count
.mapValues(lambda x: x[0]/x[1]) \ # calculate average
.sortBy(lambda x: x[1], ascending = False) \ # sort
.take(100)