首页 > 解决方案 > 获得每组的第 20 到第 80 个百分位数 - Pyspark

问题描述

我在 pyspark 数据框中有三列(下面给出的示例数据)

订单类型 客户ID 数量
一个 c1 100.2
一个 c2 1003.32
c1 222
C c3 21.3
一个 c4 1.2

我想从每个 orderType 中删除异常值。为此,我从每个 orderType 的数据中删除了前 Nth Percentile。

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

需要帮助来为大型数据集(大约 6700 万行数)实现这一点。

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

标签: pythonapache-sparkpysparkapache-spark-sqlpercentile

解决方案


您可以使用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]'
)

此处记录了该功能的用法。


推荐阅读