没有独特的模式;找到了 2 个同样常见的值

mgc*_*gcy 7 python statistics

我正在使用statistics.mode([1, 1, 2, 2, 3])查找模式,但我得到:

没有独特的模式;找到了 2 个同样常见的值

当找到多个模式时,如何输出12

Xav*_*hot 9

请注意,在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)

  • 这很巧妙,而且恰好正是我在 pandas groupby agg 调用中所需要的 (2认同)

oma*_*al8 5

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)

  • 该答案被自动标记为“低质量”。正如[帮助](https://stackoverflow.com/help/how-to-answer)中所解释的(“简洁是可以接受的,但更全面的解释更好。”),请编辑你的答案以告诉OP他在做什么错误,你如何推理以及你的代码是关于什么的,以表明你理解这个问题并使OP和未来的访问者受益。 (5认同)

小智 5

当没有唯一模式时,尝试以下方法找到最大值作为模式:

max([p[0] for p in statistics._counts([1, 1, 2, 2, 3])])
Run Code Online (Sandbox Code Playgroud)


Jay*_*llo 0

例如:

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)