繁体   English   中英

更快地计算numpy数组python中字符串出现次数的方法

[英]Faster way to count number of string occurrences in a numpy array python

我有一个numpy元组:

trainY = np.array([('php', 'image-processing', 'file-upload', 'upload', 'mime-types'),
                   ('firefox',), ('r', 'matlab', 'machine-learning'),
                   ('c#', 'url', 'encoding'), ('php', 'api', 'file-get-contents'),
                   ('proxy', 'active-directory', 'jmeter'), ('core-plot',),
                   ('c#', 'asp.net', 'windows-phone-7'),
                   ('.net', 'javascript', 'code-generation'),
                   ('sql', 'variables', 'parameters', 'procedure', 'calls')], dtype=object)

我给出了这个np.array子集的索引列表:

x = [0, 4]

和一个字符串:

label = 'php'

我想计算标签'php'在np.array的这个子集中出现的次数。 在这种情况下,答案是2。

笔记:

1)标签只会出现在元组中的最多ONCE

2)元组的长度可以是1到5。

3)列表x长度通常为7-50。

4) trainY长度约为0.8mil

我目前的代码是:

sum([1 for n in x if label in trainY[n]])

这是我的程序的性能瓶颈,我正在寻找一种方法来使它更快。 我想我们可以跳过x的循环,只是做一个矢量化的查找trainY就像trainY[x]但我无法得到一些trainY[x]东西。

谢谢。

我认为在这种情况下使用计数器可能是一个不错的选择。

from collections import Counter

c = Counter([i for j in trainY for i in j])

print c['php'] # Returns 2
print c.most_common(5) # Print the 5 most common items.

使用np.in1d平数组后,可以使用np.in1d

trainY = np.array([i for j in trainY for i in j])
ans = np.in1d(trainY, 'php').sum()
# 2

考虑构建一个表单字典:

{'string1': (1,2,5),
 'string2': (3,4,5),
 ...
}

对于每个单词,保存它在元组中出现的索引的排序列表。 希望它有意义......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM