python - GroupBy Column1,然后获取Column2上第一个/最后一个元素的所有元素(Python)
问题描述
df=(pd.DataFrame({'user_id':[1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4],'survey_id':[1,1,1,1,2,2,3,4,4,4,5,5,6,6,7,8,8,9,9,9,9,10,10,11,11,12,12],
'answer':["no","yes","no","no","yes","no","no","yes","no","yes","no","no","yes","no","no","no","yes","yes","yes","no","no","no","yes","no","yes","no","yes"]}))
df
user_id survey_id answer
0 1 1 no
1 1 1 yes
2 1 1 no
3 1 1 no
4 1 2 yes
5 1 2 no
6 1 3 no
7 2 4 yes
8 2 4 no
9 2 4 yes
10 2 5 no
11 2 5 no
12 2 6 yes
13 2 6 no
14 3 7 no
15 3 8 no
16 3 8 yes
17 3 9 yes
18 3 9 yes
19 3 9 no
20 3 9 no
21 4 10 no
22 4 10 yes
23 4 11 no
24 4 11 yes
25 4 12 no
26 4 12 yes
我想分组user_id
,然后获取的第一个元素survey_id
,并获取与此选择相关的所有元素
df_head=
user_id survey_id answer
0 1 1 no
1 1 1 yes
2 1 1 no
3 1 1 no
4 2 4 yes
5 2 4 no
6 2 4 yes
7 3 7 no
8 4 10 no
9 4 10 yes
以同样的方式我想分组user_id
,然后获取的最后一个元素survey_id
,并获取与此选择相关的所有元素
df_tail=
user_id survey_id answer
0 1 3 no
1 2 6 yes
2 2 6 no
3 3 9 yes
4 3 9 yes
5 3 9 no
6 3 9 no
7 4 12 no
8 4 12 yes
是否有一个快速的 groupby 命令来获得这个?我可以通过合并数据框来做到这一点,但我认为有一些更好的方法可以在更少的命令行中做到这一点。先感谢您
解决方案
没有合并的解决方案:
df_head = df[df.survey_id.eq(df.groupby('user_id').transform('min').survey_id)]
结果:
user_id survey_id answer
0 1 1 no
1 1 1 yes
2 1 1 no
3 1 1 no
7 2 4 yes
8 2 4 no
9 2 4 yes
14 3 7 no
21 4 10 no
22 4 10 yes
df_tail = df[df.survey_id.eq(df.groupby('user_id').transform('max').survey_id)]
结果:
user_id survey_id answer
6 1 3 no
12 2 6 yes
13 2 6 no
17 3 9 yes
18 3 9 yes
19 3 9 no
20 3 9 no
25 4 12 no
26 4 12 yes
想法是计算survey_id
per的 min/maxuser_id
并将其survey_id
与df
. 请注意,保留数据帧的原始索引。如果您需要新索引,只需在末尾添加:
df_head = df_head.reset_index(drop = True)
df_tail = df_tail.reset_index(drop = True)
推荐阅读
- tensorflow - 如何理解Text Generation RNN模型的张量维度(TensorFlow官方示例之一)
- angular - 在Angular中从父级设置子组件ngModel
- mapreduce - Netsuite 重新配置库存详细信息错误
- c++ - 如何在 C++ 中的向量向量的帮助下正确执行矩阵运算?
- javascript - webpack 供应商库未转换为 ES5
- jenkins - 在 Jenkins 中对 Node 的每个执行器执行命令
- mongodb - mongo查找不使用某人索引的数据
- excel - 非常混乱的数据:如何清理所有不一致的水平数据?[VBA]
- laravel - 如何通过刀片文件中的url传递静态值?
- logging - 在 uWSGI 中禁用 health_check 的日志