根据每组值的分位数过滤数据框

Filter dataframe based on the quantile per group of values

假设我有一个这样的数据框:

import pandas as pd
df = pd.DataFrame({'col1':['A','A', 'A', 'B','B'], 'col2':[2, 4, 6, 3, 4]})

我只想保留在 col2 处具有值的行,这些行分别小于 col1 的每个值组的值的第 x 个分位数。

例如,对于第 60 个百分位数,数据框应如下所示:

  col1  col2
0    A     2
1    A     4
2    B     3

我怎样才能在 pandas 中有效地做到这一点?

我们有 transformquantile

df[df.col2.lt(df.groupby('col1').col2.transform(lambda x : x.quantile(0.6)))]
  col1  col2
0    A     2
1    A     4
3    B     3