给定一个无序的值列表,比如
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
我怎样才能得到出现在列表中的每个值的频率,就像这样?
# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output
给定一个无序的值列表,比如
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
我怎样才能得到出现在列表中的每个值的频率,就像这样?
# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output
当前回答
你可以这样做:
import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)
输出:
(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))
第一个数组是值,第二个数组是具有这些值的元素的数量。
所以如果你想要得到一个数字数组,你应该使用这个:
np.unique(a, return_counts=True)[1]
其他回答
另一种方法是使用较重但功能强大的库——NLTK。
import nltk
fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()
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'])
下面是使用itertools的另一个简洁的替代方案。Groupby也适用于无序输入:
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))}
结果
format: {value: num_of_occurencies}
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
如果列表是排序的,你可以使用itertools标准库中的groupby(如果不是,你可以先排序,尽管这需要O(nlgn)时间):
from itertools import groupby
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
[len(list(group)) for key, group in groupby(sorted(a))]
输出:
[4, 4, 2, 1, 2]
对于一个无序列表,你应该使用:
[a.count(el) for el in set(a)]
输出为
[4, 4, 2, 1, 2]