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
After groupby, how to flatten column headers?
提问by samthebrand
I'm trying to left join multiple pandas dataframes on a single Id
column, 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 groupby
statement, 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 groupby
code:
我的groupby
代码:
step1 = pd.DataFrame(step3.groupby(['Id', 'interestingtabsplittest2__grp'])['applications'].sum())
step1.sort('applications', ascending=False).head(3)
Returns:
返回:
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=False
when doing the groupby.
注意:您可以通过as_index=False
在进行 groupby 时使用来避免此步骤。
step1 = step3.groupby(['Id', 'interestingtabsplittest2__grp'], as_index=False)['applications'].sum()