【发布时间】:2017-09-04 10:29:59
【问题描述】:
我有一个包含 3 列的数据框 - location_id、客户、集群。 以前,我按数据聚类成 5 个聚类。因此,簇列包含值 [0, 1, 2, 3, 4]。
我想将每个集群分成 2 个切片以进行下一阶段的测试。例如。 50-50片,或30-70片,或20-80片。
问题 - 如何应用将列添加到
data.groupby('cluster')?
理想结果
location_id customers cluster slice
0 149213 132817 1 1
1 578371 76655 1 0
2 91703 74048 2 1
3 154868 62397 2 1
4 1022759 59162 2 0
更新
@MaxU 的解决方案让我走上了正确的道路。该解决方案涉及使用 dataframe.assign 函数添加新列,并检查当前索引/总索引长度以分配正确比例的切片。但是,下面的代码不知何故对我不起作用。我最终将@MaxU 的解决方案拆分为单独的步骤,并且奏效了。
testgroup= (data.groupby('cluster')
.apply(lambda x: x.assign(index1=(np.arange(len(x))))
))
testgroup= (testgroup.groupby('cluster')
.apply(lambda x: x.assign(total_len=len(x))
))
testgroup['is_slice'] = ((testgroup['index1']/testgroup['total_len']) <= 0.5)
location_id customers cluster index1 total_len is_slice
0 149213 132817 1 0 12 True
1 578371 76655 1 1 12 True
2 91703 74048 1 2 12 True
3 154868 62397 1 3 12 True
4 1022759 59162 1 4 12 True
5 87016 58134 1 5 12 True
6 649432 56849 1 6 12 False
7 219163 56802 1 7 12 False
8 97704 54718 1 8 12 False
9 248455 52806 1 9 12 False
10 184828 52783 1 10 12 False
11 152887 52565 1 11 12 False
【问题讨论】:
-
请提供您原始DataFrame的示例。