gpt4 book ai didi

scala - Spark Dataframe - 在加入时实现 Oracle NVL 功能

转载 作者:行者123 更新时间:2023-12-01 01:43:30 28 4
gpt4 key购买 nike

我需要在加入两个数据帧时在 spark 中实现 NVL 功能。

输入数据帧:

ds1.show()
---------------
|key | Code |
---------------
|2 | DST |
|3 | CPT |
|null | DTS |
|5 | KTP |
---------------

ds2.show()
------------------
|key | PremAmt |
------------------
|2 | 300 |
|-1 | -99 |
|5 | 567 |
------------------

需要实现 "LEFT JOIN NVL(DS1.key, -1) = DS2.key"。
所以我是这样写的,但是缺少 NVL 或 Coalesce 函数。所以它返回了错误的值。

如何在 Spark 数据帧中加入“NVL”?
// nvl function is missing, so wrong output
ds1.join(ds1,Seq("key"),"left_outer")

-------------------------
|key | Code |PremAmt |
-------------------------
|2 | DST |300 |
|3 | CPT |null |
|null | DTS |null |
|5 | KTP |567 |
-------------------------

预期结果 :
-------------------------
|key | Code |PremAmt |
-------------------------
|2 | DST |300 |
|3 | CPT |null |
|null | DTS |-99 |
|5 | KTP |567 |
-------------------------

最佳答案

我知道一种复杂的方法。

 val df = df1.join(df2, coalesce(df1("key"), lit(-1)) === df2("key"), "left_outer")

您应该重命名一个 df 的列名“key”,并在加入后删除该列。

关于scala - Spark Dataframe - 在加入时实现 Oracle NVL 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46318577/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com