我正试图找出一个有效列表的模式,但当有多个模式时,会返回一个错误。如何修复代码中的此错误?
我想让它像[3, 3, 4, 4] => (3+4)/2 = 3.5
一样计算,如果可能的话。
import statistics
numbers = ['3', '3', '4', '4']
mode = statistics.mode(numbers)
print(f'Mode: {mode}')
这就是我得到的错误:统计。StatisticsError:没有唯一模式;发现两个相同的值
您可能有一个旧的python版本。在最近的版本(≥3.8(中,应返回第一个模式。
输出:Mode: banana
对于多种模式,使用statistics.multimode
:
import statistics
food = ['banana', 'banana', 'apple', 'apple']
mode = statistics.multimode(food)
print(f'Mode: {mode}')
输出:Mode: ['banana', 'apple']
以字符串作为数字:
from statistics import multimode, mean
numbers = ['3', '3', '4', '4']
mode = mean(map(int, multimode(numbers)))
print(f'Mode: {mode}')
输出:Mode: 3.5
您可以首先使用collections.Counter
来计算元素的出现次数,然后使用列表理解来获取模式的元素。
from collections import Counter
import statistics
result_dict = Counter(numbers)
result = [float(i) for i in result_dict.keys() if result_dict[i] == max(result_dict.values())]
statistics.mean(result)
3.5
统计模块不适用于可能存在多个";模式";。该数据集称为双峰数据集。您可以通过以下方式以编程方式处理该问题:
from collections import Counter
# The Counter function from collections module helps with counting the
# "frequency" of items occurring inside the list
food = ['banana', 'banana', 'apple', 'apple']
data_dictionary = Counter(food)
print(data_dictionary)
# Now that the count of each data-item has been generated,
# The modal, bimodal or n-modal value of the data set can be decided by
# Finding the maximum count of frequencies.
max = 0 # initiating empty variable
modal_data_items = [] # initiating empty list
for key, value in data_dictionary.items():
# If the frequency-value is more that the previously recorded
# max value, then the max value is updated and the modal_values
# list gets updated to contain the data-item
if value > max:
max = value
modal_data_items = [key]
# In the case where, there are multiple modes in the data,
# there is only a need to append more data-items (key)
# into the list of modal-items
elif value == max:
modal_data_items.append(key)
print("The modes of the given data-set are:", modal_data_items)
希望这能有所帮助!