7

How to get row counts based on one column in Python pandas. For example I have a data frame like this:

Name         NameTitle    Sex

John         Dr           m
Mona         Dr           f
Mary         Mrs          f
Tom          Mr           m
Jack         Mr           m 
Leila        Ms           f
Soro         Ms           f 
Christi      Ms           f
Mike         Mr           m  

I need to count the number of name titles based on sex. Desired output would be like this:

NameTitle    Sex    Count

Dr           m      1
Dr           f      1
Mrs          f      1
Mr           m      3
Ms           f      3

1 Answer 1

8

Use groupby + size + reset_index:

df = df.groupby(['NameTitle','Sex'], sort=False).size().reset_index(name='Count')
print (df)
  NameTitle Sex  Count
0        Dr   m      1
1        Dr   f      1
2       Mrs   f      1
3        Mr   m      3
4        Ms   f      3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.