Say I have a list of countries
l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
and then I have a list of unique countries
ul = ['India', 'China', 'Japan', 'USA']
I want to have a count of each unique country in the list in ascending order. So output should be as follows:
Japan 1
China 2
India 2
USA 2
You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears.
Method 2: Count occurrences of an element in a list Using count() The idea is to use the list method count() to count the number of occurrences.
You can use Counter from collections:
from collections import Counter
l = ["India", "China", "China", "Japan", "USA", "India", "USA"]
new_vals = Counter(l).most_common()
new_vals = new_vals[::-1] #this sorts the list in ascending order
for a, b in new_vals:
print a, b
If you don't want to use a Counter
you can count yourself (you already know the unique elements because you have ul
) using a dictionary:
l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
ul = ['India', 'China', 'Japan', 'USA']
cnts = dict.fromkeys(ul, 0) # initialize with 0
# count them
for item in l:
cnts[item] += 1
# print them in ascending order
for name, cnt in sorted(cnts.items(), key=lambda x: x[1]): # sort by the count in ascending order
print(name, cnt)
# or in case you need the correct formatting (right padding for the name):
# print('{:<5}'.format(name), cnt)
which prints:
Japan 1
China 2
India 2
USA 2
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