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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:25:07  来源:igfitidea点击:

Pandas drop group column after groupby.apply(..)

pythonpandasdataframegroup-bypandas-groupby

提问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 uidin the index in the first place by passing group_keys=Falseto the groupby

您可以uid通过传递group_keys=Falsegroupby

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_indexor droplevel:

使用reset_indexdroplevel

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_indexas Falseto remove the index from the grouped by df.

您可以设置as_indexFalse从 df 分组中删除索引。

df.groupby('uid', as_index=False)