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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With