Learn
Learn

Reputation: 548

how to count the occurrence of a groupby result in Pandas

after the below code

df[df['label'] == 'buy'].groupby('key').datee.value_counts()

i have this dataframe

label    key      datee   
buy      AAA   2018-03-14    3
         BBB   2018-01-23    3
         CCC   2018-02-19    4

then i want to count the occurrence if the number,to have something like this:

number   occurrence
3             2
4             1

the challenge for me is that, there's no header on the top of the number, please help

Upvotes: 1

Views: 46

Answers (1)

user3483203
user3483203

Reputation: 51155

Setup

df = pd.DataFrame({
    'label': ['buy' for _ in range(10)], 
    'key': ['AAA', 'AAA', 'AAA', 'BBB', 'BBB', 'BBB', 'CCC', 'CCC', 'CCC', 'CCC'],
    'date': ['2018-03-14', '2018-03-14', '2018-03-14', 
             '2018-01-23', '2018-01-23', '2018-01-23', 
             '2018-02-19', '2018-02-19', '2018-02-19', 
             '2018-02-19']
})

All you have to do is apply value_counts a second time:

df[df['label'] == 'buy'].groupby('key').date.value_counts().value_counts()

3    2
4    1
Name: date, dtype: int64

Upvotes: 3

Related Questions