簡體   English   中英

有多種模式時如何找到列表的模式 - Python

[英]How to find the mode of a list when there are multiple modes - Python

我試圖找出有效的列表模式,但是當有多種模式時,會返回錯誤。 我將如何在我的代碼中修復此錯誤?

我想使它像正常計算一樣計算它[3, 3, 4, 4] => (3+4)/2 = 3.5如果可能的話。

import statistics

numbers = ['3', '3', '4', '4']
mode = statistics.mode(numbers)
print(f'Mode: {mode}')

這是我得到的錯誤:statistics.StatisticsError: no unique mode; 找到 2 個同樣常見的值

您可能有一個舊的 python 版本。 在最近的版本(≥3.8)中,這應該返回第一種模式。

Output: Mode: banana

對於多種模式,請使用statistics.multimode

import statistics

food = ['banana', 'banana', 'apple', 'apple']
mode = statistics.multimode(food)
print(f'Mode: {mode}')

output: Mode: ['banana', 'apple']

統計模塊不適用於可能有多個“模式”的數據集。 該數據集稱為雙峰數據集。 您可以通過以下方式以編程方式解決問題:

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)

希望這可以幫助!

您可以先使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM