如何删除pandas中每组的第一行

gis*_*ang 3 python pandas

我有一个像这样的数据框:

   id  values
0   1       3
1   1       6
2   1       3
3   2       7
4   2       6
5   2       3
6   2       9
Run Code Online (Sandbox Code Playgroud)

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

   id  values
1   1       6
2   1       3
4   2       6
5   2       3
6   2       9
Run Code Online (Sandbox Code Playgroud)

我尝试通过以下方式完成:df = df.groupby('id').agg(lambda x:x[1:]),但它不起作用。

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

jez*_*ael 5

apply与以下一起使用iloc

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
Run Code Online (Sandbox Code Playgroud)

或者duplicatedboolean indexing

df = df[df['id'].duplicated()]
print (df)
   id  values
1   1       6
2   1       3
4   2       6
5   2       3
6   2       9
Run Code Online (Sandbox Code Playgroud)

细节

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