python - 根据列值创建组
问题描述
我正在尝试根据特定的 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
任何人都可以提供的任何帮助将不胜感激。
解决方案
看起来您正在寻找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
推荐阅读
- javascript - 方括号中的对象和某些键如何工作?
- html - Python3 Django Webapp HTML 测试按钮打印调试数据
- postman - Postman 未授权 Slack App
- android - 如何在 react-native 中添加破折号或虚线边框?
- django - 基于 Celery 类的任务同步运行而不是异步运行
- c# - 尝试从 Opc 服务器获取历史数据时如何修复“BadServiceUnsupported”错误
- angular - Angular Material:树节点计数
- c++ - 完美转发 const ref 扣除错误
- kotlin - kotlin 表达式自动转换时
- outlook-redemption - 文件 [filepath].ost 正在使用中,升级到 Outlook 2016 后无法访问