pandas 熊猫在 groupby.apply(..) 之后删除组列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43464410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas drop group column after groupby.apply(..)
提问by Mansumen
uid iid val
uid
1 1 1 5 5.5
2 3 1 4 3.5
2 2 1 4 3.5
2 7 1 4 3.5
2 9 1 4 3.5
2 11 1 4 3.5
From the dataframe above, I want to remove the first column, which is:
从上面的数据框中,我想删除第一列,即:
uid
1
2
2
2
2
2
and extract
并提取
uid iid val
1 1 5 5.5
3 1 4 3.5
2 1 4 3.5
7 1 4 3.5
9 1 4 3.5
11 1 4 3.5
Can someone help?
有人可以帮忙吗?
回答by piRSquared
You can avoid including the uid
in the index in the first place by passing group_keys=False
to the groupby
您可以uid
通过传递group_keys=False
给groupby
df.groupby('uid', group_keys=False).apply(lambda x: x.tail(len(x) // 5))
uid iid val
4 1 5 5.5
回答by jezrael
Use reset_index
or droplevel
:
df = df.reset_index(level=0, drop=True)
df = df.reset_index(level='uid', drop=True)
Or:
或者:
df.index = df.index.droplevel(0)
回答by disp_name
you can set as_index
as False
to remove the index from the grouped by df.
您可以设置as_index
为False
从 df 分组中删除索引。
df.groupby('uid', as_index=False)