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

问题描述 投票:0回答:4

我想在python中使用statistics.mode([1,1,2,2,3])函数来计算模式,它返回no unique mode; found 2 equally common values。这样,我想输出12。有没有人有任何好主意?

python statistics usage-statistics
4个回答
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

其他方式:

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

2
投票

尝试此函数,当没有唯一模式时,它会将最大值设置为模式:

import statistics
def find_max_mode(list1):
    list_table = statistics._counts(list1)
    len_table = len(list_table)

    if len_table == 1:
        max_mode = statistics.mode(list1)
    else:
        new_list = []
        for i in range(len_table):
            new_list.append(list_table[i][0])
        max_mode = max(new_list) # use the max value here
    return max_mode

if __name__ == '__main__':
    a = [1,1,2,2,3]
    print(find_max_mode(a)) # print 2

2
投票
from collections import Counter
c = Counter([1,1,2,2,3])
c.most_common(1)
# output
>>> [(1,2)] #the key 1, 2 occurrences.

来自文档:

“most_common([n]):返回n个最常见元素的列表及其从最常见到最少的计数。具有相同计数的元素是任意排序的”


0
投票

我刚遇到同样的问题。这是我如何简单地解决它:

def most_element(liste):
    numeral=[[liste.count(nb), nb] for nb in liste]
    numeral.sort(key=lambda x:x[0], reverse=True)
    return(numeral[0][1])

不确定这是最优雅的方式,但它做的工作:)。希望它会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.