spark数据集:数据转换

kd3sttzy  于 2021-05-29  发布在  Spark
关注(0)|答案(2)|浏览(414)

我有一个spark数据集的格式-

+--------------+--------+-----+
|name          |type    |cost |
+--------------+--------+-----+
|AAAAAAAAAAAAAA|XXXXX   |0.24|
|AAAAAAAAAAAAAA|YYYYY   |1.14|
|BBBBBBBBBBBBBB|XXXXX   |0.78|
|BBBBBBBBBBBBBB|YYYYY   |2.67|
|BBBBBBBBBBBBBB|ZZZZZ   |0.15|
|CCCCCCCCCCCCCC|XXXXX   |1.86|
|CCCCCCCCCCCCCC|YYYYY   |1.50|
|CCCCCCCCCCCCCC|ZZZZZ   |1.00|
+--------------+--------+----+

我想把它转换成一个-

public class CostPerName {
    private String name;
    private Map<String, Double> costTypeMap;
}

我想要的是,

+--------------+-----------------------------------------------+
|name          |           typeCost.                           |
+--------------+-----------------------------------------------+
|AAAAAAAAAAAAAA|(XXXXX, 0.24), (YYYYY, 1.14)                   |            
|BBBBBBBBBBBBBB|(XXXXX, 0.78), (YYYYY, 2.67), (ZZZZZ, 0.15)    |
|CCCCCCCCCCCCCC|(XXXXX, 1.86), (YYYYY, 1.50), (ZZZZZ, 1.00)    |
+--------------+-----------------------------------------------+

i、 例如,对于每个 name ,我想要一张Map (type, cost) .
实现这种转变的有效途径是什么?我可以使用一些Dataframe转换吗?我尝试了groupby,但只有在执行sum、avg等聚合查询时,它才会起作用。

bwitn5fc

bwitn5fc1#

您可以将“类型”和“成本”这两个列组合成一个新的结构列,然后按名称分组,并使用collect\u list作为聚合函数:

df.withColumn("type_cost", struct("type", "cost"))
     .groupBy("name").agg(collect_list("type_cost"))

这将产生如下Dataframe:

+--------------+---------------------------------------------+
|name          |collect_list(type_cost)                      |
+--------------+---------------------------------------------+
|AAAAAAAAAAAAAA|[[XXXXX, 0.24], [YYYYY, 1.14]]               |
|CCCCCCCCCCCCCC|[[XXXXX, 1.86], [YYYYY, 1.50], [ZZZZZ, 1.00]]|
|BBBBBBBBBBBBBB|[[XXXXX, 0.78], [YYYYY, 2.67], [ZZZZZ, 0.15]]|
+--------------+---------------------------------------------+
t2a7ltrp

t2a7ltrp2#

你可以使用 map_from_arrays() 如果您的spark版本允许:

scala> val df2 = df.groupBy("name").agg(map_from_arrays(collect_list($"type"), collect_list($"cost")).as("typeCost"))
df2: org.apache.spark.sql.DataFrame = [name: string, typeCost: map<string,decimal(3,2)>]

scala> df2.printSchema()
root
 |-- name: string (nullable = false)
 |-- typeCost: map (nullable = true)
 |    |-- key: string
 |    |-- value: decimal(3,2) (valueContainsNull = true)

scala> df2.show(false)
+--------------+---------------------------------------------+
|name          |typeCost                                     |
+--------------+---------------------------------------------+
|AAAAAAAAAAAAAA|[XXXXX -> 0.24, YYYYY -> 1.14]               |
|CCCCCCCCCCCCCC|[XXXXX -> 1.86, YYYYY -> 1.50, ZZZZZ -> 1.00]|
|BBBBBBBBBBBBBB|[XXXXX -> 0.78, YYYYY -> 2.67, ZZZZZ -> 0.15]|
+--------------+---------------------------------------------+

scala>

相关问题