python 统计list中各个元素出现的频数

您所在的位置:网站首页 统计数组中数字的个数 python 统计list中各个元素出现的频数

python 统计list中各个元素出现的频数

2023-10-21 23:29| 来源: 网络整理| 查看: 265

统计list中元素出现的频数有三种:

利用字典统计 利用Python的collection包下的Counter类统计 利用Python的pandas包下的value_counts类统计

一、利用字典统计

利用Python字典的键值对来进行统计。 逻辑就是,生成一个字典,将要统计的列表作为字典的键,然后对字典该键进行赋值,赋值方法采用字典的dict.get()函数。 Python 字典get() 函数返回指定键的值,如果值不在字典中返回默认值。

dict.get(key, default=None)

例:

a_list = ['dog', 'cat', 'dog', 'pig', 'pig', 'dog'] freq_dict = {} for x in a_list : freq_dict[x] = freq_dict.get(x, 0) + 1 print(freq_dict)

输出结果:

{'dog': 3, 'cat': 1, 'pig': 2} 二、利用Python的collection包下Counter的类

例:

from collections import Counter a = [1, 2, 3, 1, 1, 2] result = Counter(a) print result

输出结果:

{1: 3, 2: 2, 3: 1}

注:python中的collections 模块----Python标准库,是数据结构常用模块。 Counter主要功能:将元素数量统计,然后计数返回一个字典,键为元素,值为元素个数。 例:

from collections import Counter str="abcbcaccbbad" li=[2,3,43,3,45,54,33,33,1] d={'d':3,'f':4,'g':3,'h':5} #获取元素个数,返回字典 print(dict(Counter(str))) print(dict(Counter(d))) print(dict(Counter(li))) #most_common(int) 按照元素出现的次数进行从高到低的排序,返回前int个元素的字典 print(Counter(str).most_common(2)) #elements返回经过计算器Counter后的元素,返回的是一个迭代器 print(''.join(Counter(str).elements())) #update更新,做加法,加上对应的个数 x=Counter(str) x.update("sas1") print(dict(x)) #subtract,做减法,减去对于的个数 y=Counter(li) y.subtract([3,2]) print(dict(y)) print(y) #获取key和value print(list(Counter(str).items())) #字典的key和value print(list(Counter(str).keys())) #字典的key print(list(Counter(str).values())) #字典的value

输出结果:

{‘a’: 3, ‘b’: 4, ‘c’: 4, ‘d’: 1} {‘d’: 3, ‘f’: 4, ‘g’: 3, ‘h’: 5} {2: 1, 3: 2, 43: 1, 45: 1, 54: 1, 33: 2, 1: 1} [(‘b’, 4), (‘c’, 4)] aaabbbbccccd {‘a’: 4, ‘b’: 4, ‘c’: 4, ‘d’: 1, ‘s’: 2, ‘1’: 1} {2: 0, 3: 1, 43: 1, 45: 1, 54: 1, 33: 2, 1: 1} Counter({33: 2, 3: 1, 43: 1, 45: 1, 54: 1, 1: 1, 2: 0}) [(‘a’, 3), (‘b’, 4), (‘c’, 4), (‘d’, 1)] [‘a’, ‘b’, ‘c’, ‘d’] [3, 4, 4, 1]

三、Python的pandas包下的value_counts方法

例:

import pandas as pd a = [1, 2, 3, 1, 1, 2] result = pd.value_counts(a) print result

输出结果: 1 3 2 2 3 1

注:利用pandas下的value_counts(),不仅可以统计list中各个元素出现的个数,还可对矩阵中的元素进行进行统计。

例:

import pandas as pd a = pd.DataFrame([[1,2,3], [3,1,3], [1,2,1]]) result = a.apply(pd.value_counts) print result

输出结果:

0 1 2 1 2.0 1.0 1.0 # 表示元素1在第一列出现2次,在第二列出现1次,在第三列出现1次 2 NaN 2.0 NaN # 表示元素2在第一列出现0次,在第二列出现2次,在第三列出现0次 3 1.0 NaN 2.0 # 表示元素3在第一列出现1次,在第二列出现0次,在第三列出现2次


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3