2017-09-14 112 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))