我有一个如下所示的数据框 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/