一个很简单的问题:统计列表中元素出现个数、比例。
想了以下4种解决方案。我感觉pandas应该是最快的,不过在不能调用第三方库的情况下,可以试试前面几种哪个快些。
list.count()
ls = ['a','a','a','b','b','c']
countDict = dict()
proportitionDict = dict()
for i in set(ls):
countDict[i] = ls.count(i)
proportitionDict[i] = ls.count(i)/len(ls)
print(countDict)
print(proportitionDict)
dict.get()
ls = ['a','a','a','b','b','c']
countDict = dict()
proportitionDict = dict()
for i in ls:
countDict[i] = countDict.get(i,0) + 1
for i in countDict:
proportitionDict[i] = countDict[i]/len(ls)
print(countDict)
print(proportitionDict)
Counter()
from collections import Counter
ls = ['a','a','a','b','b','c']
countDict = Counter(ls)
proportitionDict = dict()
for i in countDict:
proportitionDict[i] = countDict[i]/len(ls)
print(countDict)
print(proportitionDict)
Counter()类只有自动计数功能,没有自动求比例的功能。有一个获取频数最高的前n个元素的方法:
Counter('abracadabra').most_common(1)
括号里的参数代表获取出现次数最多的前几个元素,不填参数则按频数从高到低输出所有。
pandas.Series.value_counts()
import pandas as pd
ls = ['a','a','a','b','b','c']
se = pd.Series(ls)
countDict = dict(se.value_counts())
proportitionDict = dict(se.value_counts(normalize=True))
print(countDict)
print(proportitionDict)
value_counts()返回的是Series,而且带有自动按频数排序的功能,比如想获取出现次数最多的前2个:
se.value_counts().iloc[:2]