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

2024-05-13 21:31:48 发布

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

我有以下数据框,其中两个第一行看起来像:

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

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

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


Tags: 数据方法idtimecountrypysparktemperaturestation
1条回答
网友
1楼 · 发布于 2024-05-13 21:31:48

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

使用RDDAPI和匿名函数:

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)

相关问题 更多 >