2016-10-13 14 views
0

私はスカラでスパークを使用しています。スパークスカラは、複数の列から文字列の配列を取得します

enter image description here

私は次の出力を取得する方法を知りたいのです

[文字列型文字列配列の配列でなければなりません[以下の画像の列アキュムレータを参照してください]:

入力を想像してみて私の本当のデータフレームで]

enter image description here

私は3列以上のものを持っています。私は数千の列を持っています。

希望する出力を得るにはどうすればよいですか?

答えて

1

あなたはarray機能を使用して、列の順序をマッピングすることができます:列の値がそうでない場合はゼロとヌルと異なる場合

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

は、カラム名をとり

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

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

とヌルをフィルタリングするためにUDFを使用します。

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]| 
+-----+------+----+--------------+ 
関連する問題