Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas count rows based on column

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
like image 452
raja Avatar asked May 22 '17 11:05

raja


People also ask

How do I count the number of rows in a column in Python?

Count the number of rows and columns of Dataframe using len() function. The len() function returns the length rows of the Dataframe, we can filter a number of columns using the df. columns to get the count of columns.

How do I count the number of values in a column in a DataFrame?

Use Sum Function to Count Specific Values in a Column in a Dataframe. We can use the sum() function on a specified column to count values equal to a set condition, in this case we use == to get just rows equal to our specific data point.


1 Answers

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
like image 138
jezrael Avatar answered Sep 24 '22 06:09

jezrael