アイテムのリストが与えられた場合、リストのモードは最も頻繁に発生するアイテムであることを思い出してください。
リストのモードを見つけることができるが、リストにモードがない場合にメッセージを表示する関数を作成する方法を知りたいです (たとえば、リスト内のすべての項目が 1 回しか表示されない)。関数をインポートせずにこの関数を作成したい。独自の関数をゼロから作成しようとしています。
-esque機能を備えたパッケージで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
注:CounterはPython 2.7の新機能であり、以前のバージョンでは使用できません。
Python 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などの統計ソフトウェアからリーフを取得すると、これらは最小の最も一般的な値を返すだけなので、2 つの値が同じ頻度で発生する場合は、これらのうち最小の値が返されます。例が役立つことを願っています:
>>> 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)
これら 2 つの方法の問題点は、複数のモードで機能しないことです。1 つ目はエラーを返し、2 つ目は最初のモードを返します。
セットのモードを見つけるには、次の関数を使用できます。
def mode(array):
most = max(list(map(array.count, array)))
return list(set(filter(lambda x: array.count(x) == most, array)))
短いが、なんとなく醜い:
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
少し長くなりますが、複数のモードを持つことができ、ほとんどのカウントまたはデータ型の組み合わせで文字列を取得できます。
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
なぜだけではないのですか
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
これには必要ないくつかのエラー チェックはありませんが、関数をインポートせずにモードを検出し、すべての値が 1 回しか表示されない場合はメッセージを出力します。また、同じ最大数を共有する複数のアイテムも検出しますが、それが必要かどうかは明確ではありませんでした。
この関数は、関数のモード (複数可) と、データセット内のモードの頻度 (複数可) を返します。モードがない場合 (つまり、すべての項目が 1 回しか発生しない場合)、関数はエラー文字列を返します。これは上記の 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
リストの平均値、中央値、モードを見つける方法は次のとおりです。
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]))
最小モードを探している人向け。たとえば、numpy を使用したバイモーダル分布の場合。
import numpy as np
mode = np.argmax(np.bincount(your_list))
以下は、リスト内で発生する最初のモードを取得する単純な関数です。リスト要素をキーと出現回数としてディクショナリを作成し、dict 値を読み取ってモードを取得します。
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(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 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