Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

python - After groupby, how to flatten column headers?

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

KeyError: 'Id'.

I think it 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 question seem to work.

My groupby code:

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?

question from:https://stackoverflow.com/questions/33004573/after-groupby-how-to-flatten-column-headers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're looking for .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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...