【问题标题】:How to use spark dataframe api to calculate quantile with groupBy?如何使用 spark dataframe api 通过 groupBy 计算分位数?
【发布时间】:2017-07-31 14:37:36
【问题描述】:

我有一些这样的数据:

id  country  salary
1     US      2000
2     US      3500
3     US      2600
4     JPN     2500
5     JPN     3800
6     CHN     2400
7     CHN     3200

我想按“国家”分组,然后计算薪水的 75,95,99 分位数 我该怎么办? 有没有类似计算平均值的方法,类似于

df.groupBy("country").agg(sum($"salary"))
and 
df.groupBy("country").agg(quantileFunction)

【问题讨论】:

    标签: apache-spark spark-dataframe aggregate-functions


    【解决方案1】:

    这是我为烛台图/箱须图计算分位数的方法,这是一个百分位数函数。在您的情况下,这可能有效:

    df.registerTempTable("table1")
    df2 = sqlContext.sql("Select id, 
                                 country, 
                                 percentile(salary, 75) as 75quant,
                                 percentile(salary, 95) as 95quant,
                                 percentile(salary, 99) as 99quant
                         from table1
                         group by country")
    

    【讨论】:

    • 我可以在数据框 api 中使用百分位数,例如 df.groupBy("country").agg(percentile)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 2017-10-11
    • 2016-07-28
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多