【问题标题】:How to produce multiple modes in Python?如何在 Python 中产生多种模式?
【发布时间】:2013-01-25 10:55:39
【问题描述】:

基本上我只需要弄清楚如何从 Python 中的列表中生成模式(出现频率最高的数字),无论该列表是否具有多种模式?

类似这样的:

def print_mode (thelist):
  counts = {}
  for item in thelist:
    counts [item] = counts.get (item, 0) + 1
  maxcount = 0
  maxitem = None
  for k, v in counts.items ():
    if v > maxcount:
      maxitem = k
      maxcount = v
  if maxcount == 1:
    print "All values only appear once"
  if counts.values().count (maxcount) > 1:
    print "List has multiple modes"
  else:
    print "Mode of list:", maxitem

但不是在“所有值只出现一次”或“列表有多种模式”中返回字符串,而是希望它返回它所引用的实际整数?

【问题讨论】:

  • 你想从这个开始:stackoverflow.com/a/5829377/16363
  • 啊,不,我已经看过了。我需要一些能产生模式并且只产生模式的东西,而不是其他整数以及它们出现的频率?
  • 所以你只想返回列表中元素的频率
  • @hayleyelisa 那么就拿最高数的那一个
  • 不,如果有多个模式,我需要它返回多个模式?

标签: python mode


【解决方案1】:

创建一个Counter,然后选择最常见的元素:

from collections import Counter
from itertools import groupby

l = [1,2,3,3,3,4,4,4,5,5,6,6,6]

# group most_common output by frequency
freqs = groupby(Counter(l).most_common(), lambda x:x[1])
# pick off the first group (highest frequency)
print([val for val,count in next(freqs)[1]])
# prints [3, 4, 6]

【讨论】:

  • 是的!这正是我所需要的!非常感谢!!
  • 我得到这个错误:'itertools.groupby' 对象没有属性'next'
【解决方案2】:

python 3.8 的统计模块中新增了一个功能:

import statistics as s
print("mode(s): ",s.multimode([1,1,2,2]))

输出:模式:[1, 2]

【讨论】:

    【解决方案3】:
    def mode(arr):
    
    if len(arr) == 0:
        return []
    
    frequencies = {}
    
    for num in arr:
        frequencies[num] = frequencies.get(num,0) + 1
    
    mode = max([value for value in frequencies.values()])
    
    modes = []
    
    for key in frequencies.keys():
        if frequencies[key] == mode:
            modes.append(key)
    
    return modes
    

    此代码可以处理任何列表。确保列表的元素是数字。

    【讨论】:

    • 请务必解释为什么您的答案有效以及它解决了哪些问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2020-10-14
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多