如何使用Python識別序列中出現頻率最高的專案?
問題
你需要識別序列中出現頻率最高的專案。
解決方案
我們可以使用計數器來跟蹤序列中的專案。
什麼是計數器?
“計數器”是一種對映,它為每個鍵儲存一個整數計數。更新現有鍵會增加其計數。此物件用於計算可雜湊物件的例項或作為多重集。
進行資料分析時,“計數器”是你最好的朋友之一。
此物件在Python中已經存在一段時間了,因此對於你們中的許多人來說,這將是一個快速的回顧。我們將從`collections`中匯入`Counter`開始。
from collections import Counter
傳統的字典,如果缺少鍵,將引發鍵錯誤。如果找不到鍵,Python的字典將返回鍵錯誤。
# An empty dictionary
dict = {}
# check for a key in an empty dict
dict['mystring']
# Error message
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-12-1e03564507c6> in <module>
3
4 # check for a key in an empty dict
----> 5 dict['mystring']
6
7 # Error message
KeyError: 'mystring'在這種情況下,我們如何避免鍵錯誤異常?
計數器是字典的子類,具有非常類似字典的行為,但是,如果你查詢缺少的鍵而不是引發鍵錯誤,它只會返回零。
# define the counter c = Counter()
# check for the unavailable key
print(f"Output\n{c['mystring']}")輸出
0
c['mystring'] += 1
print(f"Output\n{c}")輸出
Counter({'mystring': 1})示例
print(f"Output\n{type(c)}")輸出
<class 'collections.Counter'>
序列中出現頻率最高的專案
計數器的另一個優點是你可以使用一個物件列表,它會為你計數。它使我們無需構建迴圈即可構建計數器。
Counter
('Peas porridge hot peas porridge cold peas porridge in the pot nine days old'.split())輸出
Counter({'Peas': 1,
'porridge': 3,
'hot': 1,
'peas': 2,
'cold': 1,
'in': 1,
'the': 1,
'pot': 1,
'nine': 1,
'days': 1,
'old': 1})`split`的作用是將字串分割成一個單詞列表。它以空格進行分割。
“計數器”將遍歷該列表並計算所有單詞,從而給出輸出中顯示的計數。
還有更多,我還可以計算短語中最常見的單詞。
`most_common()`方法將提供出現頻率最高的專案。
count = Counter('Peas porridge hot peas porridge cold peas porridge in the pot nine days old'.split())
print(f"Output\n{count.most_common(1)}")輸出
[('porridge', 3)]示例
print(f"Output\n{count.most_common(2)}")輸出
[('porridge', 3), ('peas', 2)]示例
print(f"Output\n{count.most_common(3)}")輸出
[('porridge', 3), ('peas', 2), ('Peas', 1)]
請注意,它返回了一個元組列表。元組的第一部分是單詞,第二部分是其計數。
計數器例項的一個鮮為人知的功能是,可以使用各種數學運算輕鬆地組合它們。
string = 'Peas porridge hot peas porridge cold peas porridge in the pot nine days old' another_string = 'Peas peas hot peas peas peas cold peas' a = Counter(string.split()) b = Counter(another_string.split())
# Add counts
add = a + b
print(f"Output\n{add}")輸出
Counter({'peas': 7, 'porridge': 3, 'Peas': 2, 'hot': 2, 'cold': 2, 'in': 1, 'the': 1, 'pot': 1, 'nine': 1, 'days': 1, 'old': 1})# Subtract counts
sub = a - b
print(f"Output\n{sub}")輸出
Counter({'porridge': 3, 'in': 1, 'the': 1, 'pot': 1, 'nine': 1, 'days': 1, 'old': 1})最後,計數器在如何將資料儲存在容器中的方面非常智慧。
如上所示,它在儲存時將單詞分組在一起,允許我們將它們放在一起,這通常稱為多重集。
我們可以使用`elements`一次提取一個單詞。它不記住順序,但將短語中的所有單詞放在一起。
示例
print(f"Output\n{list(a.elements())}")輸出
['Peas', 'porridge', 'porridge', 'porridge', 'hot', 'peas', 'peas', 'cold', 'in', 'the', 'pot', 'nine', 'days', 'old']
示例
print(f"Output\n{list(a.values())}")輸出
[1, 3, 1, 2, 1, 1, 1, 1, 1, 1, 1]
示例
print(f"Output\n{list(a.items())}")輸出
[('Peas', 1), ('porridge', 3), ('hot', 1), ('peas', 2), ('cold', 1), ('in', 1), ('the', 1), ('pot', 1), ('nine', 1), ('days', 1), ('old', 1)]
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP