[英]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.