एक सूची का मोड ढूँढना


126

मदों की सूची को देखते हुए, याद रखें कि सूची का मोड वह आइटम है जो सबसे अधिक बार होता है।

मैं यह जानना चाहूंगा कि एक फ़ंक्शन कैसे बनाया जाए जो किसी सूची का मोड ढूंढ सके लेकिन यह एक संदेश प्रदर्शित करता है यदि सूची में मोड नहीं है (उदाहरण के लिए, सूची में सभी आइटम केवल एक बार दिखाई देते हैं)। मैं किसी भी फ़ंक्शन को आयात किए बिना इस फ़ंक्शन को बनाना चाहता हूं। मैं स्क्रैच से अपना फंक्शन बनाने की कोशिश कर रहा हूं।


क्षमा करें, लेकिन क्या आप बता सकते हैं कि 'सूची के मोड' से आपका क्या मतलब है?
विकास

5
@Vikas: मोड सबसे अक्सर होने वाला तत्व है (यदि कोई हो)। कुछ परिभाषाएँ इसे ऐसे सभी तत्वों के अंकगणित माध्य लेने के लिए बढ़ाती हैं यदि एक से अधिक हैं।
जेरेमी रोमन

यहाँ कई गलत जवाब! उदाहरण के लिए assert(mode[1, 1, 1]) == Noneऔर assert(mode[1, 2, 3, 4]) == None। एक नंबर एक होने के लिए mode, यह सूची में कम से कम एक अन्य संख्या की तुलना में समय की अधिक संख्या होने चाहिए, और यह चाहिए नहीं केवल सूची में नंबर हो।
लाइफबैलेंस

जवाबों:


156

आप maxफ़ंक्शन और एक कुंजी का उपयोग कर सकते हैं । पर एक नज़र डालें अजगर अधिकतम समारोह 'कुंजी' और लैम्ब्डा अभिव्यक्ति का उपयोग करते हुए

max(set(lst), key=lst.count)

6
यह ओपी का सही जवाब है, इस पर विचार करते हुए इसे किसी भी अतिरिक्त आयात की आवश्यकता नहीं है। अच्छी नौकरी, डेविड
जेसन परम

12
मुझे लगता है कि यह अंदर चलेगा O(n**2)। क्या यह?
lirtosiast

7
यह द्विघात रनटाइम है
Padraic Cunningham

20
बस इस्तेमाल भी कर सकता था max(lst, key=lst.count)। (और मैं वास्तव में एक सूची नहीं कहूंगा list।)
स्टीफन पोचमैन

2
क्या कोई समझा सकता है कि यह द्वि-मोडिकल वितरण के लिए कैसे काम करता है? जैसे a = [22, 33, 11, 22, 11]; print(max(set(a), key=a.count))रिटर्न 11। क्या यह हमेशा न्यूनतम मोड लौटाएगा? और यदि हां, तो क्यों?
battey

99

आप पैकेज Counterमें आपूर्ति का उपयोग कर सकते हैं collectionsजिसमें एक- modeफ़ंक्शन होता है

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

नोट: काउंटर अजगर 2.7 में नया है और पहले के संस्करणों में उपलब्ध नहीं है।


19
सवाल बताता है कि उपयोगकर्ता खरोंच से एक फ़ंक्शन बनाना चाहता है - यानी, कोई आयात नहीं।
dbliss

3
आपकी अंतिम पंक्ति एक सूची देती है, जिसमें एक मोड और इसकी आवृत्ति वाली टपल शामिल होती है। सिर्फ एक मोड का उपयोग करने के लिए Counter(your_list_in_here).most_common(1)[0][0]। यदि एक से अधिक मोड हैं तो यह एक मनमाना रिटर्न देता है।
रॉरी डॉल्टन

1
मान लीजिए कि nसबसे आम हैं modes। यदि काउंटर (your_list_in_here) .AST_common (1) [0] [0] आपको पहला मोड मिलता है, तो आप एक और सबसे आम कैसे प्राप्त करेंगे mode? बस के 0साथ पिछले बदलें 1? एक modeको अपनी पसंद के अनुसार अनुकूलित करने के लिए एक समारोह बना सकते हैं ..

1
यदि एक से अधिक मोड हैं, तो मैं इन नंबरों में से सबसे बड़ा कैसे वापस कर सकता हूं?
अकिन हवन

59

पायथॉन 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'

17
मोड ([1, 1,1,1, 2, 3, 3, 3, 3, 4]) का उपयोग करने पर त्रुटि फेंकता है जहां 1 और 3 समान संख्या में दोहराते हैं। आदर्श रूप से, सबसे छोटी संख्या को लौटाना चाहिए जो सबसे बड़ी लेकिन बराबर संख्या में होती है। स्टैटिस्ट्रेट: कोई अनोखी विधा नहीं; 2 समान रूप से समान मूल्य पाए
aman_novice

4
इस 3.4 आँकड़े पैकेज उपयोग नहीं किया है, लेकिन scipy.stats.mode छोटी से छोटी वापस आ जाएगी, इस मामले 1. मैं करूंगा में, हालांकि, कुछ मामलों में त्रुटि के फेंक पसंद करते हैं ...
शब्दों का

2
@aman_novice, इस मुद्दे को पायथन 3.8 में हल किया गया था। docs.python.org/3/library/statistics.html#statistics.mode
माइकल डी

2
अजगर 3.8 भी जोड़ा गया multimode, जो एक से अधिक होने पर कई मोड लौटाता है।
स्टासन

30

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.]))

क्या कोई कारण है कि आप इस सम्मेलन का पालन नहीं कर सकते हैं?


4
जब कई होते हैं तो केवल सबसे छोटी विधा को क्यों लौटाया जाता है?
zyxue

@zyxue सरल सांख्यिकीय सम्मेलन
संतुष्ट करता है

2
@ संतुष्ट हैं और अगर कई हैं तो इसे सबसे बड़ी विधा में वापस लाने के लिए?
अकिन हवन

25

पायथन में एक सूची के मोड को खोजने के कई सरल तरीके हैं जैसे:

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)))

3
मोड का उपयोग करते हुए, दो तत्वों के एक ही समय में होने पर त्रुटि देता है।
अभिषेक मिश्रा

क्षमा करें, इस टिप्पणी को वास्तव में देर से देखा। आंकड़े। मोड (सरणी) कई मोड के साथ एक त्रुटि लौटाएगा, लेकिन अन्य तरीकों में से कोई भी नहीं करता है।
मैथविज़र्ड

7

सूची खाली होने पर काम नहीं करने वाले समुदाय के उत्तर को विस्तारित करना, यहां मोड के लिए कार्य कोड है:

def mode(arr):
        if arr==[]:
            return None
        else:
            return max(set(arr), key=arr.count)

3

मामले में आप या तो सबसे छोटे, सबसे बड़े या सभी तरीकों में रुचि रखते हैं:

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

2

मैंने इस आसान फ़ंक्शन को मोड खोजने के लिए लिखा था।

def mode(nums):
    corresponding={}
    occurances=[]
    for i in nums:
            count = nums.count(i)
            corresponding.update({i:count})

    for i in corresponding:
            freq=corresponding[i]
            occurances.append(freq)

    maxFreq=max(occurances)

    keys=corresponding.keys()
    values=corresponding.values()

    index_v = values.index(maxFreq)
    global mode
    mode = keys[index_v]
    return mode

2
यदि 2 आइटम समान नहीं हैं, तो यह विधि विफल हो जाएगी। घटनाओं का।
अक्षयनागपाल

2

लघु, लेकिन किसी तरह बदसूरत:

def mode(arr) :
    m = max([arr.count(a) for a in arr])
    return [x for x in arr if arr.count(x) == m][0] if m>1 else None

एक शब्दकोश का उपयोग करना, थोड़ा कम बदसूरत:

def mode(arr) :
    f = {}
    for a in arr : f[a] = f.get(a,0)+1
    m = max(f.values())
    t = [(x,f[x]) for x in f if f[x]==m]
    return m > 1 t[0][0] else None

2

थोड़ा लंबा है, लेकिन कई मोड हो सकते हैं और डेटाटिप्स के अधिकांश काउंट या मिश्रण के साथ स्ट्रिंग प्राप्त कर सकते हैं।

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 

2

एक नंबर एक होने के लिए mode, यह तुलना में समय की अधिक संख्या होने चाहिए कम से कम एक अन्य नंबर सूची में, और यह चाहिए नहीं केवल सूची में नंबर हो। इसलिए, मैंने @ mathwizurd के उत्तर ( differenceविधि का उपयोग करने के लिए ) को इस प्रकार दर्शाया है:

def mode(array):
    '''
    returns a set containing valid modes
    returns a message if no valid mode exists
      - when all numbers occur the same number of times
      - when only one number occurs in the list 
      - when no number occurs in the list 
    '''
    most = max(map(array.count, array)) if array else None
    mset = set(filter(lambda x: array.count(x) == most, array))
    return mset if set(array) - mset else "list does not have a mode!" 

ये परीक्षण सफलतापूर्वक पास होते हैं:

mode([]) == None 
mode([1]) == None
mode([1, 1]) == None 
mode([1, 1, 2, 2]) == None 

1

सिर्फ क्यों नहीं

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"
  elif counts.values().count (maxcount) > 1:
    print "List has multiple modes"
  else:
    print "Mode of list:", maxitem

यह कुछ त्रुटि जाँच नहीं है जो इसे होनी चाहिए, लेकिन यह किसी भी फ़ंक्शन को आयात किए बिना मोड को खोज लेगा और एक संदेश प्रिंट करेगा यदि सभी मान एक बार दिखाई देते हैं। यह एक ही अधिकतम गणना को साझा करने वाले कई मदों का भी पता लगाएगा, हालांकि यह स्पष्ट नहीं था कि क्या आप ऐसा चाहते थे।


तो क्या करने की कोशिश कर रहा है कि एक ही गिनती को प्रदर्शित करने वाली कई वस्तुओं का पता लगाया जाए और फिर उसी गिनती के साथ सभी वस्तुओं को प्रदर्शित किया जाए
Bluelantern

क्या आपने वास्तव में खुद यह कोशिश की है? यहाँ मेरे कोड से विस्तार करने के लिए यह एक ही गिनती के साथ सभी वस्तुओं को मुद्रित करने के लिए काफी सीधा है।
lxop

1

यह फ़ंक्शन किसी फ़ंक्शन के मोड या मोड को वापस नहीं करता है, चाहे कितने भी हों, साथ ही डेटासेट में मोड या मोड की आवृत्ति। यदि कोई मोड नहीं है (यानी सभी आइटम केवल एक बार होते हैं), फ़ंक्शन एक त्रुटि स्ट्रिंग देता है। यह ऊपर A_nagpal के फ़ंक्शन के समान है, लेकिन मेरी विनम्र राय में, अधिक पूर्ण है, और मुझे लगता है कि यह समझने के लिए इस प्रश्न को पढ़ना किसी भी पायथन नौसिखियों (जैसे कि वास्तव में आपके लिए) को समझना आसान है।

 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जैसे कि 'अगर हालत: इंडेंट बढ़ाओ के साथ अगली लाइन ValueRrror (' इस डेटा सेट के लिए कोई मोड नहीं है। सभी मान केवल एक बार होते हैं। ') यहां विभिन्न प्रकारों की एक सूची है। त्रुटियाँ आप उठा सकते हैं।

1

यह सभी मोड लौटाएगा:

def mode(numbers)
    largestCount = 0
    modes = []
    for x in numbers:
        if x in modes:
            continue
        count = numbers.count(x)
        if count > largestCount:
            del modes[:]
            modes.append(x)
            largestCount = count
        elif count == largestCount:
            modes.append(x)
    return modes

1

बिना किसी आयात के सूची का मोड खोजने वाला सरल कोड:

nums = #your_list_goes_here
nums.sort()
counts = dict()
for i in nums:
    counts[i] = counts.get(i, 0) + 1
mode = max(counts, key=counts.get)

कई मोड के मामले में, इसे न्यूनतम नोड वापस करना चाहिए।


0
def mode(inp_list):
    sort_list = sorted(inp_list)
    dict1 = {}
    for i in sort_list:        
            count = sort_list.count(i)
            if i not in dict1.keys():
                dict1[i] = count

    maximum = 0 #no. of occurences
    max_key = -1 #element having the most occurences

    for key in dict1:
        if(dict1[key]>maximum):
            maximum = dict1[key]
            max_key = key 
        elif(dict1[key]==maximum):
            if(key<max_key):
                maximum = dict1[key]
                max_key = key

    return max_key

0
def mode(data):
    lst =[]
    hgh=0
    for i in range(len(data)):
        lst.append(data.count(data[i]))
    m= max(lst)
    ml = [x for x in data if data.count(x)==m ] #to find most frequent values
    mode = []
    for x in ml: #to remove duplicates of mode
        if x not in mode:
        mode.append(x)
    return mode
print mode([1,2,2,2,2,7,7,5,5,5,5])

0

यहां एक साधारण फ़ंक्शन है जो किसी सूची में होने वाले पहले मोड को प्राप्त करता है। यह सूची तत्वों के साथ चाबियाँ और घटनाओं की संख्या के रूप में एक शब्दकोश बनाता है और फिर मोड प्राप्त करने के लिए प्रमुख मूल्यों को पढ़ता है।

def findMode(readList):
    numCount={}
    highestNum=0
    for i in readList:
        if i in numCount.keys(): numCount[i] += 1
        else: numCount[i] = 1
    for i in numCount.keys():
        if numCount[i] > highestNum:
            highestNum=numCount[i]
            mode=i
    if highestNum != 1: print(mode)
    elif highestNum == 1: print("All elements of list appear once.")

0

यदि आप एक स्पष्ट दृष्टिकोण चाहते हैं, तो कक्षा के लिए उपयोगी और केवल समझ के आधार पर सूचियों और शब्दकोशों का उपयोग करके, आप कर सकते हैं:

def mode(my_list):
    # Form a new list with the unique elements
    unique_list = sorted(list(set(my_list)))
    # Create a comprehensive dictionary with the uniques and their count
    appearance = {a:my_list.count(a) for a in unique_list} 
    # Calculate max number of appearances
    max_app = max(appearance.values())
    # Return the elements of the dictionary that appear that # of times
    return {k: v for k, v in appearance.items() if v == max_app}

0
#function to find mode
def mode(data):  
    modecnt=0
#for count of number appearing
    for i in range(len(data)):
        icount=data.count(data[i])
#for storing count of each number in list will be stored
        if icount>modecnt:
#the loop activates if current count if greater than the previous count 
            mode=data[i]
#here the mode of number is stored 
            modecnt=icount
#count of the appearance of number is stored
    return mode
print mode(data1)

आपको अपना जवाब टिप्पणियों या अधिक विवरणों के साथ स्पष्ट करना चाहिए
माइकल

0

यहां बताया गया है कि आप सूची का माध्य, माध्यिका और मोड कैसे पा सकते हैं:

import numpy as np
from scipy import stats

#to take input
size = int(input())
numbers = list(map(int, input().split()))

print(np.mean(numbers))
print(np.median(numbers))
print(int(stats.mode(numbers)[0]))

0
import numpy as np
def get_mode(xs):
    values, counts = np.unique(xs, return_counts=True)
    max_count_index = np.argmax(counts) #return the index with max value counts
    return values[max_count_index]
print(get_mode([1,7,2,5,3,3,8,3,2]))

0

न्यूनतम मोड की तलाश करने वालों के लिए, उदाहरण के लिए: द्वि-मोडल वितरण का मामला, संख्यात्मक रूप से।

import numpy as np
mode = np.argmax(np.bincount(your_list))

0

डेटा सेट का मोड सदस्य हैं जो सेट में सबसे अधिक बार होते हैं। यदि दो सदस्य हैं जो समान संख्या के साथ सबसे अधिक बार दिखाई देते हैं, तो डेटा में दो मोड होते हैं। इसे बिमोडल कहा जाता है ।

यदि 2 से अधिक मोड हैं, तो डेटा को मल्टीमॉडल कहा जाएगा । यदि डेटा सेट में सभी सदस्य समान संख्या में दिखाई देते हैं, तो डेटा सेट में कोई भी मोड नहीं है

निम्नलिखित फ़ंक्शन डेटा की दी गई सूची में मोड (मोड)modes() खोजने के लिए काम कर सकते हैं :

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")

आउटपुट:

# 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)
There is NO mode in the data set
# For a list of stings/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']

यदि हम इन पैकेजों से किसी फ़ंक्शन को आयात numpyया pandasकॉल नहीं करना चाहते हैं, तो यह समान आउटपुट प्राप्त करने के लिए, modes()फ़ंक्शन के रूप में लिखा जा सकता है:

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")
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.