以双峰分布显示两种模式

时间:2015-03-22 19:00:09

标签: python dictionary statistics mode

我的程序遇到了一些麻烦,它应该找到一个数字列表的模式。它大部分都在工作,但是当我知道有2个时它只显示一种模式,并且想知道是否还有显示它们的两种方式。

    number_counts = {}
    mode = 0
    for i in order:
        if i in number_counts:
            number_counts[i] += 1
        else:
            number_counts[i] = 1
    for i in number_counts:
        most_values = max(number_counts.values())
    for key, value in number_counts.items():
        if  most_values == value:
            mode = key

4 个答案:

答案 0 :(得分:3)

当然,您可以列出模式(复数):

modes = []
for key, value in number_counts.items():
        if  most_values == value:
            modes.append(key)

然后根据需要处理列表,例如:

number_of_modes = len(modes)
if number_of_modes == 1:
    print('There is only one mode: {}'.format(modes[0]))
else:
    print('There are {} modes:'.format(number_of_modes))
    for mode in modes:
        print(mode)

答案 1 :(得分:1)

number_counts = {}
mode = []
most_values = 0

for i in order:
    if i in number_counts:
        number_counts[i] += 1
    else:
        number_counts[i] = 1
    if number_counts[i] > most_values:
        most_values = number_counts[i]
for key, value in number_counts.iteritems():
    if  most_values == value:
        mode.append(key)

答案 2 :(得分:1)

以下是使用collections.Counter及其most_common方法执行此操作的一种方法:

from collections import Counter
from itertools import takewhile
counter = Counter([1,1,2,3,3,4,5,6,7])
if counter: # Avoid IndexError on mostCommon below
    mostCommon = counter.most_common() # store once, avoid calling again
    maxCount = mostCommon[0][1] # maxCount is 2 for this example
    modes = [t[0] for t in takewhile(lambda x: x[1] == maxCount, mostCommon)]
else:
    modes = [] #  There are no modes for an empty iterable.
# Now modes references the list [1, 3]

答案 3 :(得分:0)

这是一个使用collections.Counter

的简单双线程
from collections import Counter

order = [3, 5, 4, 7, 4, 3, 4, 7, 3, 6]
number_counts = Counter(order)
>>>> Counter({3: 3, 4: 3, 7: 2, 5: 1, 6: 1})

modes = [val for val,count in number_counter.items()
             if count == max(number_counter.values()) ]
>>> [3, 4]

我是独立于Shashank编写的,只能在以后阅读。 itertools.takewhile确实是从Counter.most_common()

获取所有模式的优雅方式