Python groupby 之后,如何展平列标题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33004573/
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-08-19 12:36:42  来源:igfitidea点击:

After groupby, how to flatten column headers?

pythonpandasdataframe

提问by samthebrand

I'm trying to left join multiple pandas dataframes on a single Idcolumn, but when I attempt the merge I get warning:

我试图在单个Id列上加入多个 Pandas 数据框,但是当我尝试合并时,我收到警告:

KeyError: 'Id'.

密钥错误:'Id'。

I thinkit might be because my dataframes have offset columns resulting from a groupbystatement, but I could very well be wrong. Either way I can't figure out how to "unstack" my dataframe column headers. None of the answers at this questionseem to work.

认为这可能是因为我的数据帧具有由groupby语句产生的偏移列,但我很可能是错误的。无论哪种方式,我都无法弄清楚如何“取消堆叠”我的数据框列标题。这个问题的答案似乎都不起作用。

My groupbycode:

我的groupby代码:

step1 = pd.DataFrame(step3.groupby(['Id', 'interestingtabsplittest2__grp'])['applications'].sum())
step1.sort('applications', ascending=False).head(3)

Returns:

返回:

offset headers

偏移标题

How to get those offset headers into the top level?

如何将这些偏移标题放入顶层?

采纳答案by Andy Hayden

You're looking for .reset_index().

您正在寻找.reset_index().

In [11]: df = pd.DataFrame([[2, 3], [5, 6]], pd.Index([1, 4], name="A"), columns=["B", "C"])

In [12]: df
Out[12]:
   B  C
A
1  2  3
4  5  6

In [13]: df.reset_index()
Out[13]:
   A  B  C
0  1  2  3
1  4  5  6


Note: That you can avoid this step by using as_index=Falsewhen doing the groupby.

注意:您可以通过as_index=False在进行 groupby 时使用来避免此步骤。

step1 = step3.groupby(['Id', 'interestingtabsplittest2__grp'], as_index=False)['applications'].sum()