如何将多列连接成单列(没有先前的数据知识)?

Ale*_*rte 6 scala apache-spark apache-spark-sql

假设我有以下数据帧:

agentName|original_dt|parsed_dt|   user|text|
+----------+-----------+---------+-------+----+
|qwertyuiop|          0|        0|16102.0|   0|
Run Code Online (Sandbox Code Playgroud)

我希望创建一个新的数据框,其中还有一列具有该行所有元素的串联:

agentName|original_dt|parsed_dt|   user|text| newCol
+----------+-----------+---------+-------+----+
|qwertyuiop|          0|        0|16102.0|   0| [qwertyuiop, 0,0, 16102, 0]
Run Code Online (Sandbox Code Playgroud)

注意:这只是一个例子.列数和名称未知.它是动态的.

Jac*_*ski 7

TL; DR使用structDataset.columns操作员的功能.

引用struct函数的scaladoc :

struct(colName:String,colNames:String*):Column创建一个组成多个输入列的新结构列.

有两种变体:基于字符串的列名或使用Column表达式(这使您可以更灵活地计算要应用于连接列的计算).

Dataset.columns:

columns:Array [String]以数组形式返回所有列名.


您的案例如下:

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]|
+----------+-----------+---------+-------+----+--------------------------+
Run Code Online (Sandbox Code Playgroud)


Sha*_*ala 6

我认为这非常适合您的情况,这里有一个例子

val spark =
    SparkSession.builder().master("local").appName("test").getOrCreate()
  import spark.implicits._
  val data = spark.sparkContext.parallelize(
    Seq(
      ("qwertyuiop", 0, 0, 16102.0, 0)
    )
  ).toDF("agentName","original_dt","parsed_dt","user","text")


  val result = data.withColumn("newCol", split(concat_ws(";",  data.schema.fieldNames.map(c=> col(c)):_*), ";"))        
  result.show()

+----------+-----------+---------+-------+----+------------------------------+
|agentName |original_dt|parsed_dt|user   |text|newCol                        |
+----------+-----------+---------+-------+----+------------------------------+
|qwertyuiop|0          |0        |16102.0|0   |[qwertyuiop, 0, 0, 16102.0, 0]|
+----------+-----------+---------+-------+----+------------------------------+
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!