如何将 first() 与列具有空值的函数一起使用,并将其按 pyspark 中的另一列分组?

How to use first() with a function where column has null values and group it by another column in pyspark?

我有一个 DF,我想在其中计算第一个可能的值作为“A”列(不为空)中的 chr() 并将结果添加到按“日期”列分组的新列“C” ”。 (作为信息 chr(97)=a)

结果应该是这样的:

+----------+----------+---+---+
|Date      |A         |B  |C  |
+----------+----------+---+---+
|21.02.2022|null      |12  |a  |
|21.02.2022|null      |23  |a  |
|21.02.2022|97        |25  |a  |
|22.02.2022|98        |28  |b  |
|22.02.2022|120       |29  |b  |
|22.02.2022|121       |19  |b  |
|22.02.2022|null      |10  |b  |
+----------+----------+---+---+

您可以使用按 Date 划分的 collect_list 窗口函数来获取 A 值数组。

我假设“第一个可能的值”是指每个日期的最低值。否则,您的问题定义不明确,因为除非调用 sort().orderBy(),否则 Spark 不会保留数据框中行的顺序。

如果假设正确,你可以这样解决:

from pyspark.sql import Window, functions as F
(
    df
    .withColumn('C', F.first('A', ignorenulls=True).over(Window.partitionBy('Date').orderBy('A')))
    .withColumn('C', F.chr('C'))
)