以下是示例DF:
Car Model Colors
Toyota RAV4 Red, Black
Toyota Camry Red, White
(可以列出任意数量的颜色)
如何将初始DF更改为此(不 复制每行并按前2列的匹配数进行计数)?
Toyota Black 1
Toyota Red 2
Toyota White 1
(数字表示每种颜色的!each!汽车制造商有多少种型号)
PS 这是我对这个问题的看法:
val folded = rdd
.groupBy(_.manufacturer)
.mapValues(_.foldLeft(mutable.HashMap.empty[String, Long])((hm, el) => el.colors.foreach(color => hm(color) = hm(color) + 1)))
这给了我计数。尽管我不确定如何从“ 折叠”中生成所需的DF。
答案 0 :(得分:2)
首先,您需要拆分颜色列,然后将其分解,最后按颜色和汽车分组, 尝试以下代码;
scala> val initialDf = spark.createDataFrame(List(("Toyota","RAV4","Red,Black"),("Toyota","Camry","Red,White"))).toDF("Car","Model","Colors")
scala> initialDf.select($"Car",explode(split($"Colors",",")).as("Color")).groupBy($"Car",$"Color").agg(count($"Color").as("cnt")).show()
+------+-----+---+
| Car|Color|cnt|
+------+-----+---+
|Toyota|White| 1|
|Toyota| Red| 2|
|Toyota|Black| 1|
+------+-----+---+