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
1.0k views
in Technique[技术] by (71.8m points)

python - Sum columns by level in a pandas MultiIndex DataFrame

I have my df with multi-index columns. All of my values are in float, and I want to merge values with in first level of multi-index. Please see below for detail.

first        bar                 baz                 foo   
second       one       two       one       two       one    
A       0.895717  0.805244  1.206412  2.565646  1.431256    
B       0.410835  0.813850  0.132003  0.827317  0.076467    
C       1.413681  1.607920  1.024180  0.569605  0.875906 

first        bar                 baz                 foo   

A       (0.895717+0.805244) (1.206412+2.565646)  1.431256    
B       (0.410835+0.813850) (0.132003+0.827317)  0.076467    
C       (1.413681+1.607920) (1.024180+0.569605)  0.875906 

The values are actually added (I just didn't feel like doing all this :)). Bottom line is that I just want to level-up(higher level I guess) and within the index, add all the values. Please let me know a good way to do this. Thank you!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I believe you're looking for a groupby along the first axis.

df.groupby(level=0, axis=1).sum()

Or (more succinctly),

df.sum(level=0, axis=1)

The level argument to sum implies grouping.


df

first  bar     baz     foo    
second one two one two one two
A        2   3   3   4  10   8
B       22  16   7   3   2  26
C        4   5   1   9   6   5

df.sum(level=0, axis=1)

first  bar  baz  foo
A        5    7   18
B       38   10   28
C        9   10   11

Performance wise, there's hardly any difference between the two methods outlined above (the latter is a few ticks faster).


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

...