简体   繁体   中英

Pandas: How to merge value counts in a grouped dataframe

I have a dataset that currently looks as follows:

    Date        CAT1    CAT2
1   2017-02-23  AA      BB
2   2017-02-23  CC      AA
3   2017-02-23  CC      BB
4   2017-02-24  BB      BB
5   2017-02-24  AA      BB
6   2017-02-25  CC      CC

I am looking for a nice Pythonic way to find the total value counts of each category type grouped by date as such:

Date        CAT_TOT  
2017-02-23  AA        2 
            BB        2
            CC        2
2017-02-24  AA        1 
            BB        3
            CC        0
2017-02-25  AA        0  
            BB        0
            CC        2

Many thanks in advance!!

You can melt the data to a long format prior to using groupby.

pd.melt(df, id_vars=['Date']).groupby(['Date','value']).count()

                      variable
Date       value
2017-02-23 AA            2
           BB            2
           CC            2
2017-02-24 AA            1
           BB            3
2017-02-25 CC            2

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