首页 > 解决方案 > 根据列值创建组

问题描述

我正在尝试根据特定的 DataFrame 列值创建用户组。我想根据total_usage指标创建整个 DataFrame 人口的 10 个用户组。下面显示了一个示例 DataFrame df

user_id   total_usage
1         10
2         10
3         20
4         20
5         30
6         30
7         40
8         40
9         50
10        50
11        60
12        60
13        70
14        70
15        80
16        80
17        90
18        90
19        100
20        100

df只是整个 DataFrame 的一个片段,它有超过 6000 条记录,但是我希望只有 10 个用户组。

我想要的输出示例如下所示。

user_id   total_usage  user_group
1         10           10th_group
2         10           10th_group
3         20           9th_group
4         20           9th_group
5         30           8th_group
6         30           8th_group
7         40           7th_group
8         40           7th_group
9         50           6th_group
10        50           6th_group
11        60           5th_group
12        60           5th_group
13        70           4th_group
14        70           4th_group
15        80           3th_group
16        80           3th_group
17        90           2nd_group
18        90           2nd_group
19        100          1st_group
20        100          1st_group

任何人都可以提供的任何帮助将不胜感激。

标签: pythonpandas

解决方案


看起来您正在寻找qcut,但顺序相反

df['user_group'] = 10 - pd.qcut(df['total_usage'], np.arange(0,1.1, 0.1)).cat.codes

输出,它不是序数,但我希望它能做到:

0     10
1     10
2      9
3      9
4      8
5      8
6      7
7      7
8      6
9      6
10     5
11     5
12     4
13     4
14     3
15     3
16     2
17     2
18     1
19     1
dtype: int8

推荐阅读