【问题标题】:Get 20th to 80th Percentile of each group - Pyspark获得每组的第 20 到第 80 个百分位数 - Pyspark
【发布时间】:2021-02-02 17:09:09
【问题描述】:

我在 pyspark 数据框中有三列(示例数据如下)

orderType customerId amount
A c1 100.2
A c2 1003.32
B c1 222
C c3 21.3
A c4 1.2

我想从每个 orderType 中删除异常值。为了做到这一点,我从每个 orderType 的数据中删除了前 Nth Percentile。

例如对于 N = 10,对于每个组,我将根据数量和 partitionBy orderType 获取第 10 到第 90 个百分位数的数据。

需要帮助来为大型数据集(大约 6700 万行计数)实现该功能。

如果在这种情况下适用,也有人可以帮助可能在分区上使用分位数。

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql percentile


    【解决方案1】:

    你可以使用approx_percentile,然后过滤:

    import pyspark.sql.functions as F
    
    df2 = df.withColumn(
        'percentile',
        F.expr("approx_percentile(amount, array(0.2, 0.8), 100) over (partition by orderType)")
    ).filter(
        'amount between percentile[0] and percentile[1]'
    )
    

    函数的使用记录在here

    【讨论】:

      猜你喜欢
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 2020-08-07
      • 2021-12-25
      • 2013-01-13
      相关资源
      最近更新 更多