python - 如何通过分组返回前 N% 的 Pandas DataFrame?

标签 python pandas dataframe group-by pandas-groupby

我有一个如下所示的数据框 df:

Customer   Revenue  Products  Cluster
Jon         100         5        A
Janet       225         12       C
Jim         75          2        B
Stacy       95          4        A
John        125         5        B
Bob         325         20       C
Megan       75          2        A
Stacy       95          4        A

对于 100k 条记录依此类推。

我正在尝试返回按集群分组的前 2% 的收入客户。 我知道这行不通,但我认为它给出了我正在尝试做的事情的总体思路:

df.groupby('cluster').len(df['cluster'])/100 <= .2

尝试按收入按集群取回前 2% 客户的数据框。

最佳答案

IIUC,看起来你可以使用 GroupBy.quantile 然后过滤结果:

# "Cluster" is the grouper, and
# "Revenue" is the column to calculate the quantile on. 
df[df['Revenue'] >= df.groupby('Cluster')['Revenue'].transform('quantile', 0.98)]

  Customer  Revenue  Products Cluster
0      Jon      100         5       A
4     John      125         5       B
5      Bob      325        20       C

关于python - 如何通过分组返回前 N% 的 Pandas DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56710407/

相关文章:

r - 如何通过 R 中的 For 循环创建多个线性回归模型?

Python MySQL 日期格式

python - Pandas 和 h5py 以不同方式加载相同数据(ndarray)

python - 如何清理 pandas 中的电话号码

r - 在非连续时间序列中找到某个时间范围内的最大值

r - 在R中的数据集中通过id查找两个字符的组合

python - pip install 在 OpenShift 中失败,错误信息为 Permission Denied

Python 只查找具有特定长度数字的字符串

python - 仅将列表长度等于 1 的行转换为字符串

python - 如果第二个 df 之间存在匹配,如何从它们获取项目