scala - 在 Spark 中使用 "when"函数填充数据框

标签 scala apache-spark spark-dataframe

我有一个看起来像这样的数据框

 df1:
 image-id  colorList
 -------------------------
 id1       [Red,Blue]  
 id2       [White,Grey]      

现在我想使用如下所示的 df1 创建一个新的 Dataframe

 df2:
 image-id  isRed  isBlue  isWhite  isGrey
 ----------------------------------------
 id1       1      1       0        0
 id2       0      0       1        1 

我正在尝试使用以下代码,但由于类型不匹配,它无法正常工作

val df2 = df1.withColumn("image-id",$"image-id")
.withColumn("isRed", when($"colorList" contains "Red",1).otherwise(0))

我试过了

val df2 = df1.withColumn("image-id",$"image-id")
.withColumn("isRed", when($"colorList" contains Seq("Red"),1).otherwise(0))

我收到这条消息

Unsupported literal type class scala.collection.immutable.$colon$colon List(Red)

我可以选择在 df1展开 colorList,但这会使我的表格过于复杂。

最佳答案

你要找的是array_contains函数,而不是Column.contains(后者只适用于StringType列和检查字符串值是否包含子字符串):

df1.withColumn("isRed", when(array_contains($"colorList", "Red"),1).otherwise(0))

关于scala - 在 Spark 中使用 "when"函数填充数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43590374/

相关文章:

scala - 使一个 sbt 配置依赖于另一个

scala - () => Int 和 Unit => Int 之间有什么区别? Scala 中的 "()"到底是什么类型?

scala - 状态 Monad 中的 Monadic 归约

apache-spark - 在 Spark 中读取 HDFS 时的任务数

scala - 合成两张 map

java - 无法为 IntelliJ IDE 加载 native hadoop 库

python-3.x - 如何在 PySpark 中广播 RDD?

mysql - Apache spark如何计算分区以及分区在executor中是如何处理的

scala - 比较Spark中两个数据框中的列

scala - Scala中的函数如何返回多个DataFrame?