prosource

목록 모드 찾기

probook 2023. 7. 17. 21:12
반응형

목록 모드 찾기

항목 목록을 지정하면 목록의 모드가 가장 자주 발생하는 항목임을 기억하십시오.

목록의 모드를 찾을 수 있지만 목록에 모드가 없는 경우(예: 목록의 모든 항목이 한 번만 표시됨) 메시지를 표시하는 기능을 만드는 방법을 알고 싶습니다.저는 어떤 기능도 수입하지 않고 이 기능을 만들고 싶습니다.저는 처음부터 제 기능을 만들기 위해 노력하고 있습니다.

사용할 수 있습니다.max기능과 키.'키'와 람다 식을 사용한 파이썬 최대 함수를 살펴보세요.

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

다음을 포함하는 패키지에서 제공된 를 사용할 수 있습니다.mode-esque 함수

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

참고: 카운터는 python 2.7의 새로운 버전이며 이전 버전에서는 사용할 수 없습니다.

Python 3.4는 이 방법을 포함하므로 다음과 같이 간단합니다.

>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
 3

목록에는 숫자뿐만 아니라 모든 유형의 요소를 포함할 수 있습니다.

>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
 'red'

SciPyMATLAB과 같은 일부 통계 소프트웨어를 모방하면 가장 일반적인 값이 가장 작기 때문에 두 값이 동일하게 자주 발생하면 가장 작은 값이 반환됩니다.다음과 같은 사례가 도움이 되기를 바랍니다.

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

데이터 집합의 모드는 집합에서 가장 자주 발생하는 구성원입니다.같은 횟수로 가장 자주 나타나는 두 멤버가 있으면 데이터에는 두 가지 모드가 있습니다.이것은 바이모달이라고 불립니다.

If there are more than 2 modes, then the data would be called multimodal. If all the members in the data set appear the same number of times, then the data set has no mode at all.

다음 함수 모드()는 주어진 데이터 목록에서 모드를 찾을 수 있습니다.

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

가져오기를 원하지 않는 경우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")

저는 모드를 찾기 위해 이 편리한 기능을 작성했습니다.

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

짧지만 왠지 못생겼습니다.

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

이 함수는 데이터 집합에 있는 모드의 빈도뿐만 아니라 함수의 모드를 개수에 상관없이 반환합니다.모드가 없는 경우(즉, 모든 항목이 한 번만 발생함) 함수는 오류 문자열을 반환합니다.이것은 위의 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

가 숫가다같을경이 되는 mode목록에 있는 하나 이상의 다른 숫자보다 더 많은 횟수가 발생해야 하며, 목록에 있는 유일한 숫자가 아니어야 합니다.그래서 저는 (방법을 사용하기 위해) @mathwizurd의 답을 다음과 같이 리팩터링했습니다.

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 

목록의 평균, 중위수 및 모드를 찾을 수 있는 방법은 다음과 같습니다.

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

가져오기 없이 목록의 모드를 찾는 간단한 코드:

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)

여러 모드의 경우 최소 노드를 반환해야 합니다.

왜 그냥

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

이 기능에는 몇 가지 오류 검사가 필요하지 않지만 함수를 가져오지 않고 모드를 검색하고 모든 값이 한 번만 나타나면 메시지가 인쇄됩니다.또한 동일한 최대 개수를 공유하는 여러 항목을 검색합니다. 이 항목을 원하는지 여부는 명확하지 않습니다.

모든 모드가 반환됩니다.

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

최소 모드(예: numpy를 사용하는 바이모달 분포의 경우)를 찾는 사람.

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

좋아요! 그래서 커뮤니티는 이미 많은 답을 가지고 있고 그 중 일부는 다른 기능을 사용했고 여러분은 원하지 않습니다.
매우 간단하고 쉽게 이해할 수 있는 기능을 만들 수 있습니다.

import numpy as np

#Declare Function Name
def calculate_mode(lst):

다음 단계는 목록에서 고유 요소와 해당 주파수를 찾는 것입니다.

unique_elements,freq = np.unique(lst, return_counts=True)

모드 가져오기

max_freq = np.max(freq)   #maximum frequency
mode_index = np.where(freq==max_freq)  #max freq index
mode = unique_elements[mode_index]   #get mode by index
return mode

lst =np.array([1,1,2,3,4,4,4,5,6])
print(calculate_mode(lst))
>>> Output [4]

내 뇌가 처음부터 완전히 하기로 결정한 방법.효율적이고 간결함 :) (jk lol)

import random

def removeDuplicates(arr):
    dupFlag = False

    for i in range(len(arr)):
        #check if we found a dup, if so, stop
        if dupFlag:
            break

        for j in range(len(arr)):
            if ((arr[i] == arr[j]) and (i != j)):
                arr.remove(arr[j])
                dupFlag = True
                break;

    #if there was a duplicate repeat the process, this is so we can account for the changing length of the arr
    if (dupFlag):
        removeDuplicates(arr)
    else:
        #if no duplicates return the arr
        return arr

#currently returns modes and all there occurences... Need to handle dupes
def mode(arr):
    numCounts = []

    #init numCounts
    for i in range(len(arr)):
        numCounts += [0]

    for i in range(len(arr)):
        count = 1
        for j in range(len(arr)):
            if (arr[i] == arr[j] and i != j):
                count += 1
        #add the count for that number to the corresponding index
        numCounts[i] = count

    #find which has the greatest number of occurences
    greatestNum = 0
    for i in range(len(numCounts)):
        if (numCounts[i] > greatestNum):
            greatestNum = numCounts[i]

    #finally return the mode(s)
    modes = []
    for i in range(len(numCounts)):
        if numCounts[i] == greatestNum:
            modes += [arr[i]]
    
    #remove duplicates (using aliasing)
    print("modes: ", modes)
    removeDuplicates(modes)
    print("modes after removing duplicates: ", modes)
    
    return modes


def initArr(n):
    arr = []
    for i in range(n):
        arr += [random.randrange(0, n)]
    return arr

#initialize an array of random ints
arr = initArr(1000)
print(arr)
print("_______________________________________________")

modes = mode(arr)

#print result
print("Mode is: ", modes) if (len(modes) == 1) else print("Modes are: ", modes)
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
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])

다음은 목록에서 발생하는 첫 번째 모드를 가져오는 간단한 함수입니다.목록 요소를 키와 발생 횟수로 사전을 만든 다음 딕트 값을 읽어 모드를 얻습니다.

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

명확한 접근 방식을 원하며, 수업에 유용하고 이해를 통해 목록과 사전만 사용하려면 다음을 수행할 수 있습니다.

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}
#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)
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]))

다음을 시도해 보십시오.이 값은 O(n)이며 부동 소수점(또는 int) 리스트를 반환합니다.철저하게 자동으로 테스트됩니다.collections.defaultdict를 사용하지만, 저는 당신이 그것을 사용하는 것에 반대하지 않는다고 생각합니다.또한 https://stromberg.dnsalias.org/ ~strombrg/stdev.message에서도 확인할 수 있습니다.

def compute_mode(list_: typing.List[float]) -> typing.List[float]:
    """                       
    Compute the mode of list_.

    Note that the return value is a list, because sometimes there is a tie for "most common value".
                                                                        
    See https://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list
    """                                                                                                        
    if not list_:
        raise ValueError('Empty list')
    if len(list_) == 1:           
        raise ValueError('Single-element list')
    value_to_count_dict: typing.DefaultDict[float, int] = collections.defaultdict(int)
    for element in list_:
        value_to_count_dict[element] += 1
    count_to_values_dict = collections.defaultdict(list)
    for value, count in value_to_count_dict.items():   
        count_to_values_dict[count].append(value)                           
    counts = list(count_to_values_dict)
    if len(counts) == 1:                                                                            
        raise ValueError('All elements in list are the same')          
    maximum_occurrence_count = max(counts)
    if maximum_occurrence_count == 1:
        raise ValueError('No element occurs more than once')
    minimum_occurrence_count = min(counts)
    if maximum_occurrence_count <= minimum_occurrence_count:
        raise ValueError('Maximum count not greater than minimum count')
    return count_to_values_dict[maximum_occurrence_count]

언급URL : https://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list

반응형