I need to find the frequency of elements in an unordered list
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
output->
b =
num=[3,2,3,5,5,3,7,6,4,6,7,2]
print ('\nelements are:\t',num)
count_dict={}
for elements in num:
count_dict[elements]=num.count(elements)
print ('\nfrequency:\t',count_dict)
Data. Let's say we have a list:
fruits = ['banana', 'banana', 'apple', 'banana']
Solution. Then we can find out how many of each fruit we have in the list by doing this:
import numpy as np
(unique, counts) = np.unique(fruits, return_counts=True)
{x:y for x,y in zip(unique, counts)}
Output:
{'banana': 3, 'apple': 1}
def frequencyDistribution(data):
return {i: data.count(i) for i in data}
print frequencyDistribution([1,2,3,4])
...
{1: 1, 2: 1, 3: 1, 4: 1} # originalNumber: count
Here's another succint alternative using itertools.groupby
which also works for unordered input:
from itertools import groupby
items = [5, 1, 1, 2, 2, 1, 1, 2, 2, 3, 4, 3, 5]
results = {value: len(list(freq)) for value, freq in groupby(sorted(items))}
results
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
from collections import Counter
a=["E","D","C","G","B","A","B","F","D","D","C","A","G","A","C","B","F","C","B"]
counter=Counter(a)
kk=[list(counter.keys()),list(counter.values())]
pd.DataFrame(np.array(kk).T, columns=['Letter','Count'])
For your first question, iterate the list and use a dictionary to keep track of an elements existsence.
For your second question, just use the set operator.