如何使用同一列中的值填充 Pyspark Dataframe 列中的空值,其在另一列中的对应值相同

How to fill null values in a Pyspark Dataframe column with values from the same column, whose corresponding value in another column is same

我有以下数据:

df=

user_id user_name
101 abc
102 def
null ghi
104 ghi
null abc
104 ghi
102 def
101 abc

预期输出=

user_id user_name
101 abc
102 def
104 ghi
104 ghi
101 abc
104 ghi
102 def
101 abc

我尝试使用以下代码: 代码 1=

df.where(df.user_id.isNotNull()).select("user_id", "user_name").distinct().show()

输出:

user_id user_name
101 abc
102 def
104 ghi

第二个代码=

df.filter(F.col("user_id").isNull()).withColumn("user_id", F.when(df.user_id.isNull(), "a")).show()

输出:

user_id user_name dep
a ghi test
a abc dev

我需要以某种方式在 1 个代码中使用这两个代码行,以便可以更新“a”并获得所需的输出。有人可以帮忙吗?

您可以将 code1 连接到原始数据框并使用 coalesce 填充值。 coalesce 取任一列中的前 non-null 个值。

# I add renaming of column to avoid the duplicate column name.
code1 = (df.where(df.user_id.isNotNull())
        .select("user_id", "user_name")
        .withColumnRenamed("user_id", "fill_user_id")
        .distinct())

# Join with original dataframe and fill the value
df = (df.join(code1, on="user_name", how="left")
     .select(F.coalesce("user_id", "fill_user_id").alias("user_id"), "user_name"))

结果

+-------+---------+
|user_id|user_name|
+-------+---------+
|    104|      ghi|
|    104|      ghi|
|    104|      ghi|
|    101|      abc|
|    101|      abc|
|    101|      abc|
|    102|      def|
|    102|      def|
+-------+---------+

另一种解决方案是使用Window 函数来填充。使用 Window 函数,您只需使用 1 个函数即可填充缺失值。我将 firstignorenulls=True 选项一起使用,以获取具有相同 user_name.

的第一个 non-null 值
df = df.withColumn("user_id", 
         F.first("user_id", ignorenulls=True).over(Window.partitionBy("user_name")))