我试图用ColX中的值填充ColY中的空值,同时将输出存储为我的DataFrame Col_new中的新列。我在databricks中使用pyspark,但我对此很新。
样本数据如下:
ColX ColY
apple orange
pear null
grapefruit pear
apple null
所需的输出如下所示:
ColX ColY Col_new
apple orange orange
pear null pear
grapefruit pear pear
apple null apple
我尝试了几行代码无济于事。我的最新尝试如下:
.withColumn("Col_new", col('ColX').select(coalesce('ColY')))
任何帮助将不胜感激。非常感谢。
列ColY
和ColX
都应该作为coalesce
的参数提供:
df = spark.createDataFrame([
("apple", "orange"),
("pear", None),
("grapefruit", "pear"),
("apple", None)
]).toDF("ColX", "ColY")
from pyspark.sql.functions import coalesce
df.withColumn("ColNew", coalesce("ColY", "ColX")).show()
+----------+------+------+
| ColX| ColY|ColNew|
+----------+------+------+
| apple|orange|orange|
| pear| null| pear|
|grapefruit| pear| pear|
| apple| null| apple|
+----------+------+------+
coalesce
将从列列表中返回第一个非空值。你只传递一列,所以coalesce
没有效果。
在这种情况下,正确的语法是:
from pyspark.sql.functions import coalesce
df = df.withColumn("Col_new", coalesce('ColY', 'ColX'))
这意味着取ColY
的值,除非它是null
,在这种情况下取ColX
的值。
在这种情况下,您还可以使用when
作为等效逻辑:
from pyspark.sql.functions import when
df = df.withColumn(
"Col_new",
when(col("ColY").isNull(), col("ColX")).otherwise(col("ColY"))
)