简体   繁体   English

我如何在 scala 中使用 nvl function

[英]How can i use nvl function in scala

I am trying to code the following:我正在尝试编写以下代码:

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

When I execute this, I get an error value nvl not found.当我执行这个时,我得到一个错误值 nvl not found。

Please help me to solve this issue.请帮我解决这个问题。

In Spark its called coalesce, you can check this article for more details在 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|
+----+------+---------+

In your case it may look like this:在您的情况下,它可能看起来像这样:

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

You can use a when-otherwise construct as well - see the snippet below:您也可以使用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