Spark Scala从多列中获取字符串类型的数组 [英] Spark scala get an array of type string from multiple columns

查看:355
本文介绍了Spark Scala从多列中获取字符串类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Scala中使用spark。

I am using spark with scala.

想象一下输入内容:

我想知道如何获得以下输出[请参见下图的列累加器],该输出应为类型为 String Array [String] 的数组

I would like to know how to get the following output [see the column accumulator on the following image] which should be a Array of type String Array[String]

在我的真实数据框中,我有3个以上列。我有数千列。

In my real dataframe I have more than 3 columns. I have several thousand of column.

如何获得所需的输出?

推荐答案

您可以使用 array 函数并映射一系列列:

You can use an array function and map a sequence of columns:

import org.apache.spark.sql.functions.{array, col, udf} 

val tmp = array(df.columns.map(c => when(col(c) =!= 0, c)):_*)

其中

when(col(c) =!= 0, c)


如果列值不为零,则

采用列名,否则为null。

takes a column name if column value is different than zero and null otherwise.

并使用UDF过滤空值:

and use an UDF to filter nulls:

val dropNulls = udf((xs: Seq[String]) => xs.flatMap(Option(_)))
df.withColumn("accumulator", dropNulls(tmp))

具有示例数据:

val df = Seq((1, 0, 1), (0, 1, 1), (1, 0, 0)).toDF("apple", "orange", "kiwi")

您首先得到:

+-----+------+----+--------------------+
|apple|orange|kiwi|                 tmp|
+-----+------+----+--------------------+
|    1|     0|   1| [apple, null, kiwi]|
|    0|     1|   1|[null, orange, kiwi]|
|    1|     0|   0| [apple, null, null]|
+-----+------+----+--------------------+

最后:

+-----+------+----+--------------+
|apple|orange|kiwi|   accumulator|
+-----+------+----+--------------+
|    1|     0|   1| [apple, kiwi]|
|    0|     1|   1|[orange, kiwi]|
|    1|     0|   0|       [apple]|
+-----+------+----+--------------+

这篇关于Spark Scala从多列中获取字符串类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆