python - 获得每组的第 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。
解决方案
您可以使用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]'
)
此处记录了该功能的用法。
推荐阅读
- java - Java/Jackson - TypeReference() 是如何工作的?
- google-apps-script - 如何知道点击了哪个菜单项?
- javascript - CMS 的 Google Analytics API 授权(单一授权)
- angular - 在另一个框架内的特定 DOM 元素上引导 Angular 2+ 应用程序
- docker - docker里面的docker gitlab-ci.yml
- php - 无法从一个页面重定向到另一个页面
- sql - sql表中新增行的主键,vb.net
- python - 为什么我的位置查找功能出现值错误?
- spring - 事务不使用弹簧回滚
- abstract-syntax-tree - Ada 使用 ASIS 修改源代码(Ada Semantics 接口规范)