2017-09-14 115 views
0

使用數組類型的列值我有兩列,listA存儲爲Seq[String]valB存儲爲String一個數據幀。我想創建一個第三列valC,這將是int型的,其價值是
iff valB is present in listA then 1 otherwise 0如何CASE語句

我試圖做以下幾點:

val dfWithAdditionalColumn = df.withColumn("valC", when($"listA".contains($"valB"), 1).otherwise(0)) 

但是星火未能執行這一點,給了以下錯誤:

cannot resolve 'contains('listA', 'valB')' due to data type mismatch: argument 1 requires string type, however, 'listA' is of array type.; 

如何在CASE語句中使用數組類型列值?

感謝, Devj

回答

1

你可以寫一個簡單的UDF,將檢查元素數組中存在的:

val arrayContains = udf((col1: Int, col2: Seq[Int]) => if(col2.contains(col1)) 1 else 0) 

然後只是把它並傳遞正確必要的列順序:

df.withColumn("hasAInB", arrayContains($"a", $"b")).show 

+---+---------+-------+ 
| a|  b|hasAInB| 
+---+---------+-------+ 
| 1| [1, 2]|  1| 
| 2|[2, 3, 4]|  1| 
| 3| [1, 4]|  0| 
+---+---------+-------+ 
2

你應該使用array_contains

import org.apache.spark.sql.functions.{expr, array_contains} 

df.withColumn("valC", when(expr("array_contains(listA, valB)"), 1).otherwise(0))