pandas groupby 分组取每组的前几行记录方法
作者:徐三少北 时间:2021-06-19 05:52:20
直接上例子。
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 |
来源:https://blog.csdn.net/uvyoaa/article/details/79157786
标签:pandas,groupby,分组,前几行
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Access 2002的三个实用技巧
2007-10-22 12:22:00
Python曲线拟合详解
2023-12-29 05:54:50
![](https://img.aspxhome.com/file/2023/7/105027_0s.jpg)
使用面向对象的技术创建高级JavaScript Web 应用程序
2008-11-03 13:00:00
![](https://img.aspxhome.com/file/UploadPic/200811/3/code-21s.gif)
Python连接Hadoop数据中遇到的各种坑(汇总)
2023-09-13 20:16:34
python pandas合并Sheet,处理列乱序和出现Unnamed列的解决
2022-08-26 06:23:41
Django中提示消息messages的设置方式
2021-08-14 20:40:51
sql函数:去掉html代码
2008-04-07 12:44:00
JavaScript for: i++ vs i–
2010-06-24 21:42:00
removeChild的障眼法
2009-12-04 12:49:00
js 返回 utf-8 字符编码是多少个字节, 函数 fUtf8BoundCheck
2010-07-31 18:59:00
ImageMagick FAQ 问题摘要
2008-10-21 13:14:00
python中文分词,使用结巴分词对python进行分词(实例讲解)
2023-03-15 13:37:30
![](https://img.aspxhome.com/file/2023/8/95778_0s.png)
开发Web应用程序的结构化过程
2009-06-01 10:52:00
![](https://img.aspxhome.com/file/UploadPic/20096/1/01-47s.png)
python实现WebSocket服务端过程解析
2022-09-14 10:45:19
![](https://img.aspxhome.com/file/2023/5/75855_0s.png)
python中如何正确使用正则表达式的详细模式(Verbose mode expression)
2022-08-28 04:07:02
![](https://img.aspxhome.com/file/2023/3/79753_0s.png)
详解Python 调用C# dll库最简方法
2022-05-22 00:20:09
![](https://img.aspxhome.com/file/2023/7/71747_0s.png)
Oracle数据库游标使用大全
2008-03-04 18:24:00
一个较新的ASP后门服务端实现代码
2011-02-16 10:41:00
Python3爬虫之urllib携带cookie爬取网页的方法
2022-07-01 14:19:02
python使用代理ip访问网站的实例
2022-02-08 08:16:36
![](https://img.aspxhome.com/file/2023/5/85105_0s.jpg)