【问题标题】:Pyspark: obtain percentage result after groupByPyspark:在groupBy之后获得百分比结果
【发布时间】:2018-08-22 10:23:34
【问题描述】:

例如,这是我的测试数据

test = spark.createDataFrame([
    (0, 1, 5, "2018-06-03", "Region A"),
    (1, 1, 2, "2018-06-04", "Region B"),
    (2, 2, 1, "2018-06-03", "Region B"),
    (3, 3, 1, "2018-06-01", "Region A"),
    (3, 1, 3, "2018-06-05", "Region A"),
])\
  .toDF("orderid", "customerid", "price", "transactiondate", "location")
test.show()

我可以得到这样的汇总数据

test.groupBy("customerid", "location").agg(sum("price")).show()

但我也想要百分比数据,像这样

+----------+--------+----------+ 
|customerid|location|sum(price)| percentage
+----------+--------+----------+ 
|         1|Region B|         2|    20%
|         1|Region A|         8|    80%
|         3|Region A|         1|    100%
|         2|Region B|         1|    100%
+----------+--------+----------+

我想知道

  • 我该怎么做?也许使用窗口函数?
  • 我可以将数据透视表变成这样吗? (带百分比和总和列)


我只在How to get percentage of counts of a column after groupby in Pandas找到了一个熊猫示例

更新:

在@Gordon Linoff 的帮助下,我可以得到百分比

from pyspark.sql.window import Window
test.groupBy("customerid", "location").agg(sum("price"))\
  .withColumn("percentage", col("sum(price)")/sum("sum(price)").over(Window.partitionBy(test['customerid']))).show()

【问题讨论】:

    标签: python sql group-by pyspark


    【解决方案1】:

    这回答了问题的原始版本。

    在 SQL 中,您可以使用窗口函数:

    select customerid, location, sum(price),
           (sum(price) / sum(sum(price)) over (partition by customerid) as ratio
    from t
    group by customerid, location;
    

    【讨论】:

    • 嗨,我现在可以让它工作了。非常感谢你。另外,我可以旋转结果吗?我已经更新了我的问题
    • @cqcn1991 。 . .新问题应作为问题提出,而不是通过编辑现有问题——甚至使对它们的答案无效。
    【解决方案2】:

    这里是一个干净的代码来解决你的问题:

    from pyspark.sql import functions as F
    from pyspark.sql.window import Window
    
    (test.groupby("customerid", "location")
          .agg(F.sum("price").alias("t_price"))
          .withColumn("perc", F.col("t_price") / F.sum("t_price").over(Window.partitionBy("customerid")))
    

    【讨论】:

      猜你喜欢
      • 2019-04-09
      • 1970-01-01
      • 2019-05-21
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      相关资源
      最近更新 更多