下面为大家分享一篇pandas groupby 分组取每组的前几行记录方法,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧
直接上例子。
import pandas as pd df = pd.DataFrame({'class':['a','a','b','b','a','a','b','c','c'],'score':[3,5,6,7,8,9,10,11,14]})
df:
class | score | |
---|---|---|
0 | a | 3 |
1 | a | 5 |
2 | b | 6 |
3 | b | 7 |
4 | a | 8 |
5 | a | 9 |
6 | b | 10 |
7 | c | 11 |
8 | c | 14 |
df.sort_values(['class','score'],ascending=[1,0],inplace=True) grouped = df.groupby(['class']).head(2)
grouped:
class | score | |
---|---|---|
5 | a | 9 |
4 | a | 8 |
6 | b | 10 |
3 | b | 7 |
8 | c | 14 |
7 | c | 11 |
相关推荐:
以上就是pandas groupby 分组取每组的前几行记录方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号