给定一个项目列表,回想一下,列表的众数是出现最频繁的项目。
我想知道如何创建一个函数,可以找到列表的众数,但如果列表没有众数(例如,列表中的所有项目仅出现一次),则显示消息。我想自己从头开始制作这个函数,而不引入任何函数。
max
函数和一个键。请参阅python max function using 'key' and lambda expression。max(set(lst), key=lst.count)
max(lst, key=lst.count)
。 (而且我真的不会把一个列表叫做 list
。) - Stefan Pochmanna = [22, 33, 11, 22, 11]; print(max(set(a), key=a.count))
返回 11
。它是否总是返回最小的众数?如果是,为什么? - batteyCounter
和collections
。from collections import Counter
data = Counter(your_list_in_here)
data.most_common() # Returns all unique items and their counts
data.most_common(1) # Returns the highest occurring item
注意:Counter是Python 2.7中的新功能,早期版本不可用。
Counter(your_list_in_here).most_common(1)[0][0]
。如果有多个众数,此方法会返回其中任意一个。 - Rory Daultonn
个最常见的mode
。如果Counter(your_list_in_here).most_common(1)[0][0]可以获取第一个mode,那么如何获取另一个最常见的mode
?只需将最后一个0
替换为1
即可吗?可以编写一个函数来自定义mode
以满足自己的需要。 - user7345804data.most_common(1)[0][0]
。 - Stefmax(data.items(), key=lambda x: (x[1], x[0]))
或者使用 from operator import itemgetter
,你可以重写为 max(data.items(), key=itemgetter(1,0))
。 - StefPython 3.4 包含方法 statistics.mode
,所以很简单:
>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
列表中可以包含任何类型的元素,不仅仅是数字:
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
参考一些统计软件,如SciPy和MATLAB,它们返回的是最常见的最小值,因此如果有两个值出现的频率相同,则返回其中较小的值。希望下面的例子能够帮助理解:
>>> from scipy.stats import mode
>>> mode([1, 2, 3, 4, 5])
(array([ 1.]), array([ 1.]))
>>> mode([1, 2, 2, 3, 3, 4, 5])
(array([ 2.]), array([ 2.]))
>>> mode([1, 2, 2, -3, -3, 4, 5])
(array([-3.]), array([ 2.]))
有没有什么理由,你不能遵循这个惯例?
有许多简单的方法可以在Python中找到列表的众数,例如:
import statistics
statistics.mode([1,2,3,3])
>>> 3
或者,你可以通过计数找到最大值
max(array, key = array.count)
这两种方法的问题在于它们无法处理多个众数。第一种方法会返回错误,而第二种方法只能返回第一个众数。
要找到一组数据的众数,可以使用以下函数:
def mode(array):
most = max(list(map(array.count, array)))
return list(set(filter(lambda x: array.count(x) == most, array)))
在扩展社区答案无法在列表为空时工作的情况下,这里是适用于模式的工作代码:
def mode(arr):
if arr==[]:
return None
else:
return max(set(arr), key=arr.count)
如果您对最小值、最大值或所有模式感兴趣:
def get_small_mode(numbers, out_mode):
counts = {k:numbers.count(k) for k in set(numbers)}
modes = sorted(dict(filter(lambda x: x[1] == max(counts.values()), counts.items())).keys())
if out_mode=='smallest':
return modes[0]
elif out_mode=='largest':
return modes[-1]
else:
return modes
def getmode(inplist):
'''with list of items as input, returns mode
'''
dictofcounts = {}
listofcounts = []
for i in inplist:
countofi = inplist.count(i) # count items for each item in list
listofcounts.append(countofi) # add counts to list
dictofcounts[i]=countofi # add counts and item in dict to get later
maxcount = max(listofcounts) # get max count of items
if maxcount ==1:
print "There is no mode for this dataset, values occur only once"
else:
modelist = [] # if more than one mode, add to list to print out
for key, item in dictofcounts.iteritems():
if item ==maxcount: # get item from original list with most counts
modelist.append(str(key))
print "The mode(s) are:",' and '.join(modelist)
return modelist
数据集的众数是指在数据集中出现次数最多的成员或成员组合。如果有两个成员出现次数相同且均为最多,则该数据集具有两个众数,这称为双峰。
Following function modes() can work to find mode(s) in a given list of data:
import numpy as np; import pandas as pd
def modes(arr):
df = pd.DataFrame(arr, columns=['Values'])
dat = pd.crosstab(df['Values'], columns=['Freq'])
if len(np.unique((dat['Freq']))) > 1:
mode = list(dat.index[np.array(dat['Freq'] == max(dat['Freq']))])
return mode
else:
print("There is NO mode in the data set")
Output:
# For a list of numbers in x as
In [1]: x = [2, 3, 4, 5, 7, 9, 8, 12, 2, 1, 1, 1, 3, 3, 2, 6, 12, 3, 7, 8, 9, 7, 12, 10, 10, 11, 12, 2]
In [2]: modes(x)
Out[2]: [2, 3, 12]
# For a list of repeated numbers in y as
In [3]: y = [2, 2, 3, 3, 4, 4, 10, 10]
In [4]: modes(y)
Out[4]: There is NO mode in the data set
# For a list of strings/characters in z as
In [5]: z = ['a', 'b', 'b', 'b', 'e', 'e', 'e', 'd', 'g', 'g', 'c', 'g', 'g', 'a', 'a', 'c', 'a']
In [6]: modes(z)
Out[6]: ['a', 'g']
If we do not want to import numpy
or pandas
to call any function from these packages, then to get this same output, modes()
function can be written as:
def modes(arr):
cnt = []
for i in arr:
cnt.append(arr.count(i))
uniq_cnt = []
for i in cnt:
if i not in uniq_cnt:
uniq_cnt.append(i)
if len(uniq_cnt) > 1:
m = []
for i in list(range(len(cnt))):
if cnt[i] == max(uniq_cnt):
m.append(arr[i])
mode = []
for i in m:
if i not in mode:
mode.append(i)
return mode
else:
print("There is NO mode in the data set")
无论函数有多少种模式,此函数都会返回模式或模式,以及数据集中模式或模式的出现频率。如果没有模式(即所有项仅出现一次),则函数将返回错误字符串。这类似于上面A_nagpal的函数,但在我看来更为完整,而且我认为对于任何Python新手(例如阁下)阅读本问题更容易理解。
def l_mode(list_in):
count_dict = {}
for e in (list_in):
count = list_in.count(e)
if e not in count_dict.keys():
count_dict[e] = count
max_count = 0
for key in count_dict:
if count_dict[key] >= max_count:
max_count = count_dict[key]
corr_keys = []
for corr_key, count_value in count_dict.items():
if count_dict[corr_key] == max_count:
corr_keys.append(corr_key)
if max_count == 1 and len(count_dict) != 1:
return 'There is no mode for this data set. All values occur only once.'
else:
corr_keys = sorted(corr_keys)
return corr_keys, max_count
return 'There is no mode for this data set. All values occur only once.'
的那一行可以通过使用traceback
将其转换为错误消息,如下所示:if condition: *next line with indent* raise ValueError('There is no mode for this data set. All values occur only once.')
。这里有一个错误类型列表,您可以引发不同类型的错误。 - user7345804
assert(mode[1, 1, 1]) == None
和assert(mode[1, 2, 3, 4]) == None
。一个数字要成为“众数”,它必须在列表中出现的次数比至少另一个数字多,并且它不能是列表中唯一的数字。 - lifebalance