我试图用来自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')))
任何帮助将不胜感激。非常感谢。
答案 0 :(得分:1)
列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|
+----------+------+------+
答案 1 :(得分:1)
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"))
)