gpt4 book ai didi

python - pyspark 中减少数据帧的最有效方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 22:15:03 26 4
gpt4 key购买 nike

我有以下数据框,第一行看起来像这样:

['station_id', 'country', 'temperature', 'time']
['12', 'usa', '22', '12:04:14']

我想按“法国”前 100 个站点的降序显示平均温度。

在 pyspark 中最好(最有效)的方法是什么?

最佳答案

我们通过以下方式将您的查询转换为 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)

关于python - pyspark 中减少数据帧的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41195378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com