LoginSignup
5
2

More than 5 years have passed since last update.

エラーを出さずに最頻値を得たいとき

Last updated at Posted at 2018-12-24

厳密でなくて良いので代表値として1個に絞るために最頻値を使いたい場面で、
statistics.modeでは同率1位のときのエラーを吐くので使いにくい。

やや無駄があるが、collections.Counterクラスを使うと良いかもしれない。

import statistics

x = ['A', 'A', 'B', 'B', 'C']

statistics.mode(x)
# StatisticsError: no unique mode; found 2 equally common values
import collections

x = ['A', 'A', 'B', 'B', 'C']

collections.Counter(x).most_common()[0][0]
# A

AとBとどちらが選ばれるかは、たぶん保証されない。

5
2
0

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