我有一個資料框,我必須根據現有列中的值創建一個新列。問題是,我不能寫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|
- ----- - ----
我知道我可以在 2 個單獨的資料幀中匯出它,然后將它們合并。但我正在尋找更有效的解決方案。
uj5u.com熱心網友回復:
創建資料框:
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|
// --- ----- --- ----
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424388.html
標籤:斯卡拉 阿帕奇火花 if 语句 apache-spark-sql 案件
