4

I would like to count number of yes and no values by Column and groupby index.

I have this dataframe :

col0  col1 col2
A     yes  no
A     no   no
B     yes  yes
B     yes  no

I want this:

   col1     col2
   yes  no  yes  no
A  1    1   0    2
B  2    0   1    1

I tried with df.pivot_table(index='my_index', aggfunc='count') but i only got

   col1     col2

A  2        2
B  2        2
5
  • @Wen, I've tried a few pivot solutions, but they don't seem to work. Any ideas? Commented Mar 30, 2018 at 17:58
  • @Wen Hmm, check that output, it seems different? Commented Mar 30, 2018 at 18:00
  • @cᴏʟᴅsᴘᴇᴇᴅ yep pd.concat([pd.crosstab(df.col0,[df.col1.astype('category')]),pd.crosstab(df.col0,[df.col2.astype('category')])],axis=1,keys=['col1','col2']) Commented Mar 30, 2018 at 18:01
  • @Wen Ah, it's definitely more complicated than a simple pivot problem... I'll reopen this question, so please post that as the answer ;) Commented Mar 30, 2018 at 18:02
  • @cᴏʟᴅsᴘᴇᴇᴅ Yep , I think so , we should reopen it Commented Mar 30, 2018 at 18:03

1 Answer 1

3

Option 1
pd.get_dummies + groupby + sum

v = pd.get_dummies(df.set_index('col0'))

v.columns = pd.MultiIndex.from_tuples(
    list(map(tuple, v.columns.str.split('_')))
)
v.sum(level=0)

     col1     col2    
       no yes   no yes
col0                  
A       1   1    2   0
B       0   2    1   1

Option 2
stack + get_dummies + unstack

(df.set_index('col0')
   .stack()
   .str.get_dummies()
   .sum(level=[0,1])
   .unstack(-1)
   .swaplevel(0, 1, axis=1)
   .sort_index(level=0, axis=1)
)

     col1     col2    
       no yes   no yes
col0                  
A       1   1    2   0
B       0   2    1   1

Option 3
crosstab + concat by @Wen

i = pd.crosstab(df.col0, df.col1.astype('category'))
j = pd.crosstab(df.col0, df.col2.astype('category'))

pd.concat([i, j], axis=1, keys=['col1','col2'])

     col1     col2    
col1   no yes   no yes
col0                  
A       1   1    2   0
B       0   2    1   1
Sign up to request clarification or add additional context in comments.

8 Comments

Man just add it to your answer, without your reminder I almost killing a good question ..pd.concat([pd.crosstab(df.col0,[df.col1.astype('category')]),pd.crosstab(df.col0,[df.col2.astype('category')])],axis=1,keys=['col1','col2'])
@Wen I didn't see your answer, please post again so I can upvote ;)
If you do not mind man, could you please adding to your answer ? feel embarrassed to post as an answer...:-(
@Wen It is a good answer, shame you did not post it yourself. I've added it, cheers
@cᴏʟᴅsᴘᴇᴇᴅ thanks! It works perfectly! Should I change the title of Question?, Wich is a good tittle for this problem?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.