pandas 常用函数记录

1.组内排序

A B
a 1
b 1
c 1
b 2
c 2
a 2
b 3
a 3
c 3

转换为如下格式:

A B
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3

代码如下

df_sorted = df.groupby('A',sort=False).apply(lambda x:x.sort_values('B',ascending=True)).reset_index(drop=True)

进行分组之后再取出组内最小的两个数据

df_head_2 = df_sorted.groupedby('A').head(2)

猜你喜欢

转载自blog.51cto.com/14592795/2452157