4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

リストの最頻値を求めたいがstatistics.mode()が例外を返してくる

Last updated at Posted at 2019-03-06

statistics.mode()メソッドはリストの最頻値を返してくれます


>>> import statistics
>>> l = [1,1,2,3] #最頻値は1
>>> statistics.mode(l)
1

OKですね
ところがリスト内に最頻値が複数存在すると,例外を返す仕様となっています

>>> l = [1,1,2,2,3] #最頻値は1と2
>>> statistics.mode(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/anaconda3/lib/python3.6/statistics.py", line 507, in mode
    'no unique mode; found %d equally common values' % len(table)
statistics.StatisticsError: no unique mode; found 2 equally common values
>>> 

###どうしよう

collections.Counter()メソッドが使えそうです

>>> l
[1, 1, 2, 2, 3]
>>> import collections
>>> collections.Counter(l).most_common() #(要素,出現回数)を出現回数順に並び替えたタプルを返す
[(1, 2), (2, 2), (3, 1)] 

とりあえず何か一つ最頻値が欲しい場合は,

>>> collections.Counter(l).most_common()[0][0]
1

で良さそうです

4
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?