Santiago
Santiago

Reputation: 31

Count if with 2 conditions - Python

I'm having some trouble solving this, so I come here for your help.

I have a dataframe with many columns, and I want to count how many cells of a specific column meet the condition of another column. In Excel this would be count.if, but I can't figure it out exactly for my problem. Let me give you an example.

Names    Detail

John      B
John      B
John      S
Martin    S
Martin    B
Robert    S

In this df for example there are 3 "B" and 3 "S" in total.

How can I get how many "B" and "S" there are for each name in column A?

Im trying to get a result dataframe like

         B      S
John     2      1
Martin   1      1
Robert   0      1

I tried

b_var = sum(1 for i in df['Names'] if i == 'John') 
s_var = sum(1 for k in df['Detail'] if k == 'B')

and then make a for? but I don't know how to do both conditions at a time, or is it better a groupby approach?

Thanks!!

Upvotes: 3

Views: 210

Answers (1)

Franco Piccolo
Franco Piccolo

Reputation: 7410

df.pivot_table(index='Names', columns='Detail', aggfunc=len)

Upvotes: 1

Related Questions