如何删除pandas中每组的第一行 [英] How to delete the first line of each group in pandas

查看:157
本文介绍了如何删除pandas中每组的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

I have a dataframe like this :

   id  values
0   1       3
1   1       6
2   1       3
3   2       7
4   2       6
5   2       3
6   2       9

我想根据id删除每组的第一行,结果应该是这样的:

And I want to delete the first line of each group based on id,the result should like this:

   id  values
1   1       6
2   1       3
4   2       6
5   2       3
6   2       9

我尝试通过:df = df.groupby('id').agg(lambda x:x[1:]),但它不起作用.

I tried it done by: df = df.groupby('id').agg(lambda x:x[1:]),but it doesn't work.

有人可以帮助我吗?提前致谢

Can someone help me?Thanks in advance

推荐答案

使用 applyiloc:

df = df.groupby('id', group_keys=False).apply(lambda x:x.iloc[1:])
#also working, not sure if generally
#df = df.groupby('id', group_keys=False).apply(lambda x:x[1:])
print (df)
   id  values
1   1       6
2   1       3
4   2       6
5   2       3
6   2       9

重复 使用 布尔索引:

df = df[df['id'].duplicated()]
print (df)
   id  values
1   1       6
2   1       3
4   2       6
5   2       3
6   2       9

详细信息:

print (df['id'].duplicated())
0    False
1     True
2     True
3    False
4     True
5     True
6     True
Name: id, dtype: bool

这篇关于如何删除pandas中每组的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆