我正在使用statistics.mode([1, 1, 2, 2, 3])查找模式,但我得到:
没有独特的模式;找到了 2 个同样常见的值
当找到多个模式时,如何输出1或2?
请注意,在Python 3.8的行为中statistics.mode已更改:
在 3.8 版更改: 现在通过返回遇到的第一个模式来处理多模式数据集。以前,当发现不止一种模式时,它会引发 StatisticsError。
在你的例子中:
from statistics import mode
mode([1, 1, 2, 2, 3])
# 1
Run Code Online (Sandbox Code Playgroud)
同样从 开始Python 3.8,您也可以使用statistics.multimode返回最常出现的值的列表,按照它们第一次遇到的顺序:
from statistics import multimode
multimode([1, 1, 2, 2, 3])
# [1, 2]
Run Code Online (Sandbox Code Playgroud)
from collections import Counter
c = Counter([1,1,2,2,3])
c.most_common(1)
# output
>>> [(1,2)] #the key 1, 2 occurrences.
Run Code Online (Sandbox Code Playgroud)
从文档:
“most_common([n]): 返回一个包含 n 个最常见元素及其从最常见到最少的计数的列表。计数相等的元素被任意排序”
小智 5
from scipy import stats as s
a=[1,1,2,2,3]
print(int(s.mode(a)[0]))
Run Code Online (Sandbox Code Playgroud)
小智 5
当没有唯一模式时,尝试以下方法找到最大值作为模式:
max([p[0] for p in statistics._counts([1, 1, 2, 2, 3])])
Run Code Online (Sandbox Code Playgroud)
例如:
lst = [1, 1, 2, 2, 3]
# test for count lst elements
lst_count = [[x, lst.count(x)] for x in set(lst)]
print lst_count
# [[1, 2], [2, 2], [3, 1]]
# remove count <= 1
lst_count = [x for x in set(lst) if lst.count(x) > 1]
print lst_count
# [1, 2]
# get 1 or 2 by index
print lst_count[0], lst_count[1]
# 1 2
Run Code Online (Sandbox Code Playgroud)
其他方式:
from collections import Counter
# change lst elements to str, for more readable
lst = ['a', 'a', 'b', 'b', 'c']
# get a dict, key is the elements in lst, value is count of the element
d_mem_count = Counter(lst)
print d_mem_count
# Counter({'a': 2, 'b': 2, 'c': 1})
for k in d_mem_count.keys():
if d_mem_count[k] > 1:
print k
# output as below
# a
# b
Run Code Online (Sandbox Code Playgroud)