[英]Best Way to Count Occurences of Each Character in a Large Dataset
我正在嘗試計算大型數據集中每個字符的出現次數。 例如,如果數據是 numpy 數組 ['A', 'AB', 'ABC'] 那么我希望 {'A': 3, 'B': 2, 'C': 1} 作為 output。我目前有一個看起來像這樣的實現:
char_count = {}
for c in string.printable:
char_count[c] = np.char.count(data, c).sum()
我遇到的問題是這對我的數據來說花費的時間太長了。 我想計算大約 14,000,000 個不同的字符串,並且此實現對於該數據量而言效率不高。 任何幫助表示贊賞!
另一種方式。
import collections
c = collections.Counter()
for thing in data:
c.update(thing)
相同的基本優勢 - 只迭代數據一次。
一種方法:
import numpy as np
from collections import defaultdict
data = np.array(['A', 'AB', 'ABC'])
counts = defaultdict(int)
for e in data:
for c in e:
counts[c] += 1
print(counts)
Output
defaultdict(<class 'int'>, {'A': 3, 'B': 2, 'C': 1})
請注意,您的代碼在data
上迭代len(string.printable)
次,而我的建議迭代一次。
一種使用字典的替代方法:
data = np.array(['A', 'AB', 'ABC'])
counts = dict()
for e in data:
for c in e:
counts[c] = counts.get(c, 0) + 1
print(counts)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.