pyspark 我怎样才能得到每个 parameter_code+county_name 的最大值和最小值

pyspark How can i get only the max and min values for each parameter_code+county_name

我目前在 google colab notebook 中使用 pyspark,在进行了一些数据清理后,我完成了一个数据框,该数据框具有: 参数代码;县名;每天的算术平均值

我需要一个 table 为每个参数给出具有最高值和最低值的县的名称

在完成这个 groupby 之后,我最终得到了我想要的东西(每个参数代码和县名都有最大值的值)但只有最大值,我还需要最小值

county_param_value_small_grouped_parameter_code = county_param_value_small.groupby('parameter_code','county_name').max('arithmetic_mean').orderBy("parameter_code","max(arithmetic_mean)",ascending=False).show(10)

我最终想要的是一个 table,每个参数代码有 2 个县名和 2 个值,分别是最高值和最低值。 但是我在操作它时遇到了很多麻烦,因为它总是 returns 一个对象,我必须一次性满足所有条件并在最后有一个 .show() 。

该问题的一个解决方案是使用 window 函数附加具有相同 parameter_code 的每一行 maxmin arithmetic_mean群组。最后筛选 arithmetic_mean 等于组的 minmax 值的行。

from pyspark.sql import functions as F
from pyspark.sql import Window as W

data = [("1", "IN", 10, ), ("1", "NL", 20, ), ("1", "DE", 15, ), ("2", "US", 100, ), ("2", "BE", 200, ), ("2", "FR", 150, )]

df = spark.createDataFrame(data, ("parameter_code", "county_name", "arithmetic_mean", ))

window_spec = W.partitionBy("parameter_code")

df.withColumn("max_arithmetic_mean", F.max("arithmetic_mean").over(window_spec))\
  .withColumn("min_arithmetic_mean", F.min("arithmetic_mean").over(window_spec))\
  .filter((F.col("arithmetic_mean") == F.col("max_arithmetic_mean")) | (F.col("arithmetic_mean") == F.col("min_arithmetic_mean")))\
  .select("parameter_code", "county_name", "arithmetic_mean").show()

输出

+--------------+-----------+---------------+
|parameter_code|county_name|arithmetic_mean|
+--------------+-----------+---------------+
|             1|         IN|             10|
|             1|         NL|             20|
|             2|         US|            100|
|             2|         BE|            200|
+--------------+-----------+---------------+