在 pyspark 数据帧的 groupby 中获取最少的行集

Getting the least set of rows in a groupby of a pyspark dataframe

我有一个包含值的数据框

#+-------+---------+-----+
#|name1  |name 2   |score|
#+-------+---------+-----+
#| abcdef| abcghi  |    3|
#| abcdef| abcjkl  |    3|
#| abcdef| abcyui  |    3|
#| abcdef| abrtyu  |    4|
#| pqrstu| pqrswe  |    2|
#| pqrstu| pqrsqw  |    2|
#| pqrstu| pqrzxc  |    3|
#+-------+---------+-----+

我需要按 name1 分组并选择得分最低的行。

我知道我可以在 name1 的 groupby 之后选择第一行,然后按升序对分数进行排序,然后选择第一行。我通过

做到这一点
joined_windows = Window().partitionBy("name1").orderBy(col("score").asc())
result = joined_df.withColumn("rn", row_number().over(joined_windows)).where(col("rn") == 1).drop("rn")

但我希望数据框包含以下值(即每组中分数最低的行集。

#+-------+---------+-----+
#|name1  |name 2   |score|
#+-------+---------+-----+
#| abcdef| abcghi  |    3|
#| abcdef| abcjkl  |    3|
#| abcdef| abcyui  |    3|
#| pqrstu| pqrswe  |    2|
#| pqrstu| pqrsqw  |    2|
#+-------+---------+-----+

要保存多个值,可以使用这样的代码:

val joined_windows = Window.partitionBy("name1")
val result = df.withColumn("rn", min($"score").over(joined_windows))
result.where($"rn"===$"score").drop("rn").show(false)

输出:

+------+------+-----+
|name1 |name 2|score|
+------+------+-----+
|abcdef|abcghi|3    |
|abcdef|abcjkl|3    |
|abcdef|abcyui|3    |
|pqrstu|pqrswe|2    |
|pqrstu|pqrsqw|2    |
+------+------+-----+

您可以按两列分组:

df \
    .groupBy('name1', 'name2') \
    .agg(F.min('score'))