Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate multiple columns into single column (with no prior knowledge on their number)?

Let say I have the following dataframe:

agentName|original_dt|parsed_dt|   user|text|
+----------+-----------+---------+-------+----+
|qwertyuiop|          0|        0|16102.0|   0|

I wish to create a new dataframe with one more column that has the concatenation of all the elements of the row:

agentName|original_dt|parsed_dt|   user|text| newCol
+----------+-----------+---------+-------+----+
|qwertyuiop|          0|        0|16102.0|   0| [qwertyuiop, 0,0, 16102, 0]

Note: This is a just an example. The number of columns and names of them is not known. It is dynamic.

like image 387
Alessandro La Corte Avatar asked May 26 '17 11:05

Alessandro La Corte


1 Answers

TL;DR Use struct function with Dataset.columns operator.

Quoting the scaladoc of struct function:

struct(colName: String, colNames: String*): Column Creates a new struct column that composes multiple input columns.

There are two variants: string-based for column names or using Column expressions (that gives you more flexibility on the calculation you want to apply on the concatenated columns).

From Dataset.columns:

columns: Array[String] Returns all column names as an array.


Your case would then look as follows:

scala> df.withColumn("newCol",
  struct(df.columns.head, df.columns.tail: _*)).
  show(false)
+----------+-----------+---------+-------+----+--------------------------+
|agentName |original_dt|parsed_dt|user   |text|newCol                    |
+----------+-----------+---------+-------+----+--------------------------+
|qwertyuiop|0          |0        |16102.0|0   |[qwertyuiop,0,0,16102.0,0]|
+----------+-----------+---------+-------+----+--------------------------+
like image 77
Jacek Laskowski Avatar answered Nov 01 '22 02:11

Jacek Laskowski