使用pyspark计算groupBy总数的百分比

时间:2018-09-11 20:27:18

标签: apache-spark pyspark

我在pyspark中有以下代码,生成的表向我显示了列的不同值及其计数。我想让另一列显示每一行代表总计数的百分比。我该怎么办?

difrgns = (df1
           .groupBy("column_name")
           .count()
           .sort(desc("count"))
           .show())

谢谢!

3 个答案:

答案 0 :(得分:2)

一个示例,它可能不适合Windowing,因为注释暗示并且是更好的方法:

# Running in Databricks, not all stuff required
from pyspark.sql import Row
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from pyspark.sql.types import *
#from pyspark.sql.functions import col

data = [("A", "X", 2, 100), ("A", "X", 7, 100), ("B", "X", 10, 100),
        ("C", "X", 1, 100), ("D", "X", 50, 100), ("E", "X", 30, 100)]
rdd = sc.parallelize(data)

someschema = rdd.map(lambda x: Row(c1=x[0], c2=x[1], val1=int(x[2]), val2=int(x[3])))

df = sqlContext.createDataFrame(someschema)

tot = df.count()

df.groupBy("c1") \
  .count() \
  .withColumnRenamed('count', 'cnt_per_group') \
  .withColumn('perc_of_count_total', (F.col('cnt_per_group') / tot) * 100 ) \
  .show()

返回:

 +---+-------------+-------------------+
| c1|cnt_per_group|perc_of_count_total|
+---+-------------+-------------------+
|  E|            1| 16.666666666666664|
|  B|            1| 16.666666666666664|
|  D|            1| 16.666666666666664|
|  C|            1| 16.666666666666664|
|  A|            2|  33.33333333333333|
+---+-------------+-------------------+

我专注于Scala,这似乎更容易。就是说,通过注释建议的解决方案使用Window,这是我在Scala中使用over()做的事情。

答案 1 :(得分:1)

您可以groupby并与agg聚合。例如,对于以下 DataFrame:

+--------+-----+
|category|value|
+--------+-----+
|       a|    1|
|       b|    2|
|       a|    3|
+--------+-----+

您可以使用:

import pyspark.sql.functions as F

df.groupby('category').agg(
    (F.count('value')).alias('count'),
    (F.count('value') / df.count()).alias('percentage')
).show()

输出:

+--------+-----+------------------+
|category|count|        percentage|
+--------+-----+------------------+
|       b|    1|0.3333333333333333|
|       a|    2|0.6666666666666666|
+--------+-----+------------------+

或者,您可以使用 SQL:

df.createOrReplaceTempView('df')

spark.sql(
    """
    SELECT category,
           COUNT(*) AS count,
           COUNT(*) / (SELECT COUNT(*) FROM df) AS ratio
    FROM df
    GROUP BY category
    """
).show()

答案 2 :(得分:1)

更多的“优化”输出,去除多余的小数并对其进行排序

import pyspark.sql.functions as func

data_fr \
.groupBy('col_name') \
.count() \
.withColumn('%', func.round((func.col('count')/count_cl)*100,2)) \
.orderBy('count', ascending=False) \
.show()
+--------------------+-----+----+
| col_name     |count|   %|
+--------------------+-----+----+
|      C.LQQQQ |30957|8.91|
|      C.LQQQQ |29688|8.54|
|      C-LQQQQ |29625|8.52|
|       CLQQQQ |29342|8.44|

..... +--------------------+-----+----+ 只显示前 20 行