分组并计算不同的产品型号百分比

时间:2017-11-22 22:01:07

标签: scala apache-spark dataframe

我有一个大型数据集,并使用此代码对每种产品的不同产品和不同型号进行分组。

val tt2 = dTestSample1.groupBy("Product", "model" )
                      .agg( count("Product") as "countItems" )
                      .withColumn("percentage", (col("countItems") / sum("countItems").over())* 100)
                      .sort("Product")

到目前为止,结果都是准确的in this table

任何人都可以帮我改进代码,以便能够计算产品中每种型号的百分比吗?

澄清this table的想法是手动完成的,可以作为一个例子。

1 个答案:

答案 0 :(得分:0)

听起来你正在寻找一个窗口功能。

val winSpec = Window.partitionBy("product")
df.withColumn("totalPerProduct", sum("countItems").over(winSpec)

然后您可以在此之后轻松计算百分比。

相关问题