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

python - Group a multi-indexed pandas dataframe by one of its levels?

Is it possible to groupby a multi-index (2 levels) pandas dataframe by one of the multi-index levels ?

The only way I know of doing it is to reset_index on a multiindex and then set index again. I am sure there is a better way to do it, and I want to know how.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, use the level parameter. Take a look here. Example:

In [26]: s

first  second  third
bar    doo     one      0.404705
               two      0.577046
baz    bee     one     -1.715002
               two     -1.039268
foo    bop     one     -0.370647
               two     -1.157892
qux    bop     one     -1.344312
               two      0.844885
dtype: float64

In [27]: s.groupby(level=['first','second']).sum()

first  second
bar    doo       0.981751
baz    bee      -2.754270
foo    bop      -1.528539
qux    bop      -0.499427
dtype: float64

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

...