将行值转换为spark数据帧中的列数组

时间:2016-03-31 11:33:24

标签: scala apache-spark spark-dataframe

我正在处理spark数据帧,我需要按列进行分组,并将分组行的列值转换为元素数组作为新列。 示例:

Input:

employee | Address
------------------
Micheal  |  NY
Micheal  |  NJ

Output:

employee | Address
------------------
Micheal  | (NY,NJ)

非常感谢任何帮助。!

2 个答案:

答案 0 :(得分:5)

这是另一种解决方案 我已将数据框转换为rdd以进行转换,并使用sqlContext.createDataFrame()将其转换回dataFrame

Sample.json

{"employee":"Michale","Address":"NY"}
{"employee":"Michale","Address":"NJ"}
{"employee":"Sam","Address":"NY"}
{"employee":"Max","Address":"NJ"}

Spark应用程序

val df = sqlContext.read.json("sample.json")

// Printing the original Df
df.show()

//Defining the Schema for the aggregated DataFrame
val dataSchema = new StructType(
  Array(
    StructField("employee", StringType, nullable = true),
    StructField("Address", ArrayType(StringType, containsNull = true), nullable = true)
  )
)
// Converting the df to rdd and performing the groupBy operation
val aggregatedRdd: RDD[Row] = df.rdd.groupBy(r =>
          r.getAs[String]("employee")
        ).map(row =>
          // Mapping the Grouped Values to a new Row Object
          Row(row._1, row._2.map(_.getAs[String]("Address")).toArray)
        )

// Creating a DataFrame from the aggregatedRdd with the defined Schema (dataSchema)
val aggregatedDf = sqlContext.createDataFrame(aggregatedRdd, dataSchema)

// Printing the aggregated Df
aggregatedDf.show()

输出:

+-------+--------+---+
|Address|employee|num|
+-------+--------+---+
|     NY| Michale|  1|
|     NJ| Michale|  2|
|     NY|     Sam|  3|
|     NJ|     Max|  4|
+-------+--------+---+

+--------+--------+
|employee| Address|
+--------+--------+
|     Sam|    [NY]|
| Michale|[NY, NJ]|
|     Max|    [NJ]|
+--------+--------+

答案 1 :(得分:4)

如果您使用的是 Spark 2.0 + ,则可以使用collect_listcollect_set。 您的查询类似于(假设您的数据框称为输入):

import org.apache.spark.sql.functions._

input.groupBy('employee).agg(collect_list('Address))

如果您对重复项没问题,请使用collect_list。如果您对重复项不满意并且只需要列表中的唯一项,请使用collect_set

希望这有帮助!