Reputation: 21
I'm trying to figure out how to count the frequency of each unique number in the below array, ranging from 1 - 17:
x3 = [ 8 12 10 9 6 6 5 11 9 10 4 12 10 7 7 7 7 9 8 7 9 6 7 8
8 10 7 9 9 5 9 7 5 12 12 10 7 6 9 8 6 8 5 11 7 9 7 9
9 7 12 10 12 11 9 11 6 7 5 8 8 7 10 8 7 9 6 10 6 13]
Using numpy, this was done by [np.equal(x3, i).sum() for i in range (1,18)]
What is the best alternative way to do this without numpy?
Upvotes: 2
Views: 535
Reputation: 11
You can also use a dictionary
numList = [1,2,3,1,2,3,4,5,3,4,5,6,7,8,7,6,2]
freq = dict()
for num in numList:
if num in freq.keys():
freq[num] += 1
else:
freq[num] = 1
print(freq)
{1: 2, 2: 3, 3: 3, 4: 2, 5: 2, 6: 2, 7: 2, 8: 1}
Upvotes: 1
Reputation: 77407
The standard collections module can do it
import collections
x3 = [1,1,2,2]
counts = collections.Counter(x3)
print(counts)
Upvotes: 3