If-If statement Scala Spark



我有一个数据帧,必须根据现有列中的值为其创建一个新列。问题是,我不能写CASE语句,因为这里它检查第一个WHEN条件,如果不满足,它将转到下一个WHEN。例如,考虑此数据帧:

+-+-----+-+
|A|B    |C|
+-+-----+-+
|1|true |1|-----> Condition 1 and 2 is satisfied Here
|1|true |0|-----> Condition 1 is satisfied here
|1|false|1|
|2|true |1|
|2|true |0|
+-+-----+-+

考虑以下CASE语句:

CASE WHEN A = 1 and  B = 'true' then 'A' 
WHEN A = 1 and  B = 'true' and C=1 then 'B'
END

它没有给我值B的行。

预期输出:

+-+-----+-+----+
|A|B    |C|D   |
+-+-----+-+----+
|1|true |1|A   |
|1|true |1|B   |
|1|true |0|A   |
|1|false|1|null|
|2|true |1|null|
|2|true |0|null|
+-+-----+-+----+

我知道我可以在两个独立的数据帧中导出它,然后将它们并集。但我正在寻找更有效的解决方案。

创建数据帧:

val df1 = Seq((1, true, 1), (1, true, 0), (1, false, 1), (2, true,  1), (2, true,  0)).toDF("A", "B", "C")
df1.show()
//  +---+-----+---+
//  |  A|    B|  C|
//  +---+-----+---+
//  |  1| true|  1|
//  |  1| true|  0|
//  |  1|false|  1|
//  |  2| true|  1|
//  |  2| true|  0|
//  +---+-----+---+

代码:

val condition1 = ($"A" === 1) && ($"B" === true)
val condition2 = condition1 && ($"C" === 1)
val arr1 = array(when(condition1, "A"), when(condition2, "B"))
val arr2 = when(element_at(arr1, 2).isNull, slice(arr1, 1, 1)).otherwise(arr1)
val df2 = df.withColumn("D", explode(arr2))
df2.show()
//  +---+-----+---+----+
//  |  A|    B|  C|   D|
//  +---+-----+---+----+
//  |  1| true|  1|   A|
//  |  1| true|  1|   B|
//  |  1| true|  0|   A|
//  |  1|false|  1|null|
//  |  2| true|  1|null|
//  |  2| true|  0|null|
//  +---+-----+---+----+

最新更新