如何在 CASE 语句中使用数组类型的列值
How to use array type column value in CASE statement
我有一个包含两列的数据框,listA
存储为 Seq[String]
,valB
存储为 String
。我想创建第三列valC
,它是Int类型,它的值是
iff valB is present in listA then 1 otherwise 0
我尝试执行以下操作:
val dfWithAdditionalColumn = df.withColumn("valC", when($"listA".contains($"valB"), 1).otherwise(0))
但 Spark 未能执行此操作并给出以下错误:
cannot resolve 'contains('listA', 'valB')' due to data type mismatch: argument 1 requires string type, however, 'listA' is of array type.;
如何在 CASE 语句中使用数组类型的列值?
谢谢,
开发
您可以编写一个简单的 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|
+---+---------+-------+
你应该使用 array_contains
:
import org.apache.spark.sql.functions.{expr, array_contains}
df.withColumn("valC", when(expr("array_contains(listA, valB)"), 1).otherwise(0))
我有一个包含两列的数据框,listA
存储为 Seq[String]
,valB
存储为 String
。我想创建第三列valC
,它是Int类型,它的值是
iff valB is present in listA then 1 otherwise 0
我尝试执行以下操作:
val dfWithAdditionalColumn = df.withColumn("valC", when($"listA".contains($"valB"), 1).otherwise(0))
但 Spark 未能执行此操作并给出以下错误:
cannot resolve 'contains('listA', 'valB')' due to data type mismatch: argument 1 requires string type, however, 'listA' is of array type.;
如何在 CASE 语句中使用数组类型的列值?
谢谢, 开发
您可以编写一个简单的 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|
+---+---------+-------+
你应该使用 array_contains
:
import org.apache.spark.sql.functions.{expr, array_contains}
df.withColumn("valC", when(expr("array_contains(listA, valB)"), 1).otherwise(0))