python 列表统计元素频数、频率

一个很简单的问题:统计列表中元素出现个数、比例。

想了以下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]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值