我有一个像这样的数据框:
id values
0 1 3
1 1 6
2 1 3
3 2 7
4 2 6
5 2 3
6 2 9
我想根据删除每组的第一行id
,结果应该是这样的:
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:])
,但它不起作用。
有人可以帮助我吗?提前致谢
Use apply http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html with 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
Or duplicated http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.duplicated.html with boolean indexing http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-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
Detail:
print (df['id'].duplicated())
0 False
1 True
2 True
3 False
4 True
5 True
6 True
Name: id, dtype: bool
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)