目次
はじめに
Pythonはデータ解析やAI開発などさまざまな用途で人気の高いプログラミング言語です。データを集計する際に便利な機能のひとつがcollections.Counter
クラスです。本記事では、Counterクラスのメソッドであるmost_common()
関数について、その使い方や活用方法を詳しく解説します。
Counter.most_common関数とは?
Counter.most_common()関数は、リストや文字列などの要素の出現回数を集計し、頻度が高い順に並べたリストを返す便利なメソッドです。
データの集計やランキングを作成する際に非常に役立ちます。
Counter.most_common関数の基本構文
基本構文は以下の通りです。
from collections import Counter
counter = Counter(iterable)
common_elements = counter.most_common([n])
iterable
: リストや文字列などの反復可能なデータn
: 上位何件の要素を取得するか(省略時はすべての要素を取得)
Counter.most_common関数の使用例
例1: リストの頻度集計
from collections import Counter
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = Counter(fruits)
print(counter.most_common())
実行結果:
[('apple', 3), ('banana', 2), ('orange', 1)]
例2: 文字列の頻度集計
from collections import Counter
text = "mississippi"
counter = Counter(text)
print(counter.most_common(3))
実行結果:
[('i', 4), ('s', 4), ('p', 2)]
Counter.most_common関数の応用例
例3: 単語の頻度分析
from collections import Counter
sentence = "apple banana apple orange banana apple orange"
words = sentence.split()
counter = Counter(words)
print(counter.most_common(2))
実行結果:
[('apple', 3), ('banana', 2)]
例4: データの上位ランキング
from collections import Counter
scores = [90, 85, 90, 70, 85, 90, 70, 70]
counter = Counter(scores)
print(counter.most_common(2))
実行結果:
[(90, 3), (70, 3)]
まとめ
Counter.most_common()関数はデータの頻度分析に便利な機能です。リストや文字列のデータを簡単に集計でき、ランキングや統計処理にも活用できます。Pythonでのデータ解析やWeb開発など、さまざまな場面で役立つため、ぜひ使いこなしてみてください。