简体   繁体   中英

Multiple Aggregate Functions based on Multiple Columns in Pandas

I am working with a Pandas df in Python. I have the following input df:

Color   Shape   Value
Blue    Square  5
Red     Square  2
Green   Square  7
Blue    Circle  9
Blue    Square  2
Green   Circle  6
Red     Circle  2
Blue    Square  5
Blue    Circle  1

I would like the following output:

Color   Shape   Count   Sum
Blue    Square  3       12
Red     Square  1       2
Green   Square  1       7
Blue    Circle  2       10
Green   Circle  1       6
Red     Circle  1       2

Looking for something like pivot_table() but do not want the hierarchical index.

OK, so I did more research and will answer this one myself, because it may be helpful for others.

The problem I am having is associated with indexing more than pivot tables. To remove the multiple index a simple:

df.reset_index()

does the trick just fine.

As a side note, I don't understand why a question like this would be down-voted. It is something not obvious in the documentation, or any of the literature I have read. It simply involves gaining a deeper insight into how these modules work, which is why people come here.

To down-vote something like this is, frankly, smug. In my opinion it defeats the purpose of this site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM