看Counter之前先复习一下字典的操作:
# 定义字典
dict1={'a':1}
# 新增键值对
dict1['b']=2
# 修改值
dict1['a']=3
输出:
{'a': 1}
{'a': 1, 'b': 2}
{'a': 3, 'b': 2}
计数器生成的结果跟字典是一个道理。
from collections import Counter
Counter的定义
# 定义空计数器
count1=Counter()
# 用已有的列表定义计数器
count2=Counter(['a','b','b','a','c'])
输出:
Counter()
Counter({'a': 2, 'b': 2, 'c': 1})
Counter的更新
# 用update更新
count2.update(a=+1)
# 用索引更新
count2['b']=5
输出:
Counter({'a': 3, 'b': 2, 'c': 1})
Counter({'a': 3, 'b': 5, 'c': 1})
这个update方法我还并没有很懂,先这么记。
找出现次数最多的元素
count2.most_common()
count2.most_common(2)
输出:
不给参数时,按数量从大到小输出所有元素,是一个列表。
[('b', 5), ('a', 1), ('c', 1)]
给参数时,只输出指定数目的元素。
[('b', 5), ('a', 1)]
Demo1
from collections import Counter
counts = Counter("""
MSFT GOOG AAPL AAPL MSFT C GOOG F
TEAM AAPL GOOG AAPL AAPL IBM NVDA
""".split())
# 改变数量
counts.update(MSFT=+2, AAPL=-3)
print('After changes:')
for symbol, freq in counts.most_common(3):
print(f' {symbol}: {freq} trade(s)')
输出:
After changes: MSFT: 4 trade(s) GOOG: 3 trade(s) AAPL: 2 trade(s)
Demo2
先读入一个csv文件如下所示:
GOOG,100,900.10
MSFT,50,68.99
AAPL,100,152.92
IBM,5,151.95
GOOG,150,901.25
AAPL,50,152.25
TEAM,100,36.91
NVDA,75,117.88
INTC,200,36.24
IBM,10,151.91
AAPL,700,152.15
GOOG,100,900.99
GOOG,50,900.12
from collections import Counter
def analyse(filename):
trades = Counter()
volumes = Counter()
totals = Counter()
with open(filename) as src:
for line in src:
inst, vol, price = line.split(',')
vol = int(vol)
price = float(price)
# 创建或更新Counter元素的值
trades[inst] += 1
volumes[inst] += vol
totals[inst] += vol*price
print('Top 5 trades by number of trades:')
for inst, freq in trades.most_common(5):
print(f'{inst}: {freq} trade(s) total of {volumes[inst]} shares, ${totals[inst]:,.2f}')
if __name__ == '__main__':
analyse('example.csv')
输出:
Top 5 trades by number of trades: GOOG: 4 trade(s) total of 400 shares, $360,302.50 AAPL: 3 trade(s) total of 850 shares, $129,409.50 IBM: 2 trade(s) total of 15 shares, $2,278.85 MSFT: 1 trade(s) total of 50 shares, $3,449.50 TEAM: 1 trade(s) total of 100 shares, $3,691.00