Soumyaansh Soumyaansh - 1 year ago 113
Python Question

Python: How to check the number of occurrences and top (n) values in a dataframe?

I want to count up the number of occurrences of countries in a dataframe, below is the sample and also find the top 2 countries by occurrence.

Date Location
0 09/17/1908 Virginia
1 07/12/1912 New Jersey
2 08/06/1913 Canada
3 09/09/1913 England
4 10/17/1913 Germany
5 03/05/1915 Belgium
6 09/03/1915 Germany
7 07/28/1916 Bulgeria
8 09/24/1916 England
9 10/01/1916 England

Result value should be something like below:

Location Count
England 3
Germany 2

Answer Source
countCollection = df['collection'].value_counts()

.value_counts() will give you a count for the items from the collection named collection in a dataFrame.

Also, as you mentioned you're new to Python, to get the final value:


will get the count value from the returned collection of counts, for the row with key "a".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download