在数据框架中为每组找到不同的百分位数

2024-09-28 22:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的日期框架结构如下:

df = pd.DataFrame({'GROUP_ID': np.random.randint(1, 7, size=100),
                     'VALUES': np.random.randint(0, 50, size=100)})
df['THRESHOLD'] = df['GROUP_ID']*5
df = df[['GROUP_ID','VALUES','THRESHOLD']]
df.sort_values(by='GROUP_ID', inplace=True)

(这只是一个例子)

列阈值实际上是每个组的百分位数(单位%)。 我需要添加一个“百分位数”列,其中每个组中的值应该有一个百分位数的数值

我试图使用groupbyapply,但我不知道如何将THRESHOLD列的值传递给quantile\percentile函数中的参数q


Tags: iddataframedfsizethresholdbynpgroup
1条回答
网友
1楼 · 发布于 2024-09-28 22:32:00

为传递给函数^{}GROUP_ID创建字典并映射具有x.name的treshold,对于具有^{}的新列,仅需要介于0和1之间的treshold:

np.random.seed(152)
df = pd.DataFrame({'GROUP_ID': np.random.randint(1, 7, size=100),
                     'VALUES': np.random.randint(0, 50, size=100)})
df['THRESHOLD'] = df['GROUP_ID'] / 15
df = df[['GROUP_ID','VALUES','THRESHOLD']]
df.sort_values(by='GROUP_ID', inplace=True)

d = dict(zip(df['GROUP_ID'], df['THRESHOLD']))
df['new'] = df.groupby('GROUP_ID')['VALUES'].transform(lambda x: x.quantile(d[x.name]))
print (df.head(20))
    GROUP_ID  VALUES  THRESHOLD       new
23         1      17   0.066667  7.733333
53         1       9   0.066667  7.733333
39         1      43   0.066667  7.733333
57         1      15   0.066667  7.733333
36         1      47   0.066667  7.733333
59         1      17   0.066667  7.733333
28         1       4   0.066667  7.733333
63         1      33   0.066667  7.733333
18         1      12   0.066667  7.733333
12         1      27   0.066667  7.733333
47         1      43   0.066667  7.733333
81         1      45   0.066667  7.733333
91         1      45   0.066667  7.733333
5          1       8   0.066667  7.733333
83         1      26   0.066667  7.733333
61         2      39   0.133333  4.200000
95         2      33   0.133333  4.200000
44         2      22   0.133333  4.200000
42         2      34   0.133333  4.200000
41         2      48   0.133333  4.200000

相关问题 更多 >