scala - Spark:如何在groupedData中获取带有条件的resultSet

时间:2017-04-17 09:11:51

标签: scala apache-spark

Dataframe有没有办法使用自己的架构?

这会产生格式数据:

Country | Class | Name | age
US, 1,'aaa',21
US, 1,'bbb',20
BR, 2,'ccc',30
AU, 3,'ddd',20
....

我想做一些像

Country | Class 1 Students | Class 2 Students
US , 2, 0
BR , 0, 1
....

条件1.国家灌浆。 条件2.只获得1或2个类值

这是源代码..

val df = Seq(("US", 1, "AAA",19),("US", 1, "BBB",20),("KR", 2, "CCC",29),
 ("AU", 3, "DDD",18)).toDF("country", "class", "name","age")

df.groupBy("country").agg(count($"name") as "Cnt")

1 个答案:

答案 0 :(得分:0)

您应该使用pivot功能。

val df = Seq(("US", 1, "AAA",19),("US", 1, "BBB",20),("KR", 2, "CCC",29),
 ("AU", 3, "DDD",18)).toDF("country", "class", "name","age")
df.groupBy("country").pivot("class").agg(count($"name") as "Cnt").show

+-------+---+---+---+
|country|  1|  2|  3|
+-------+---+---+---+
|     AU|  0|  0|  1|
|     US|  2|  0|  0|
|     KR|  0|  1|  0|
+-------+---+---+---+