繁体   English   中英

我如何在 scala 中使用 nvl function

[英]How can i use nvl function in scala

我正在尝试编写以下代码:

df.select(nvl(col("id"),0))

当我执行这个时,我得到一个错误值 nvl not found。

请帮我解决这个问题。

在 Spark 中它被称为 coalesce,您可以查看这篇文章了解更多详情

# create new column with non Null values
tmp = testDF.withColumn('newColumn', coalesce(testDF['id'], testDF['number']))

# Check the content of new df
tmp.show()

+----+------+---------+
|  id|number|newColumn|
+----+------+---------+
|   1|     1|        1|
|   2|     2|        2|
|null|     3|        3|
|   4|  null|        4|
+----+------+---------+

在您的情况下,它可能看起来像这样:

df.select(coalesce(col("id"),lit(0)))

您也可以使用when-otherwise构造 - 请参见下面的代码片段:

df = spark.createDataFrame([(1, 2), (2, None), (None, 3)], "id: int, value: int")
df.withColumn("non_null_value", when(col("value").isNull(), 0).otherwise(col("value"))).show()

+----+-----+--------------+
|  id|value|non_null_value|
+----+-----+--------------+
|   1|    2|             2|
|   2| null|             0|
|null|    3|             3|
+----+-----+--------------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM