如何创建 ArrayType[StringType] 的列 colMap,其值为 Array,元素为与值为 true 的列名称匹配的字符串?
我有这样的输入DataFrame:
+-----+-----+-----+
|col1 |col2 |col3 |
+-----+-----+-----+
|true |false|true |
|false|false|false|
|false|false|true |
+-----+-----+-----+
我想创建这样的输出数据帧:
+-----+-----+-----+------------+
|col1 |col2 |col3 |colMap |
+-----+-----+-----+------------+
|true |false|true |[col1, col3]|
|false|false|false|[] |
|false|false|true |[col3] |
+-----+-----+-----+------------+
编辑: 我发现了这个重复的问题:
Spark scala get an array of type string from multiple columns
但是想知道是否有更好的方法来实现输出?
最佳答案
您可以使用内置的高阶函数filter,而不是使用UDF从数组中过滤null
值。 .
val df = Seq((true, false, true),
(false, false, false),
(false, false, true)).toDF("col1", "col2", "col3")
df.withColumn("colMap", array(df.columns.map(c=> when(col(c) === "true", c)):_*))
.withColumn("colMap", expr("filter(colMap, c-> c is not null)"))
.show(false)
+-----+-----+-----+------------+
|col1 |col2 |col3 |colMap |
+-----+-----+-----+------------+
|true |false|true |[col1, col3]|
|false|false|false|[] |
|false|false|true |[col3] |
+-----+-----+-----+------------+
关于arrays - Spark scala 将列名称映射到值为 true 的输出 arraytype 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69190795/