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

mch*_*gun 5 python arrays string performance numpy

我有一个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)
Run Code Online (Sandbox Code Playgroud)

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

x = [0, 4]
Run Code Online (Sandbox Code Playgroud)

和一个字符串:

label = 'php'
Run Code Online (Sandbox Code Playgroud)

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

笔记:

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

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

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

4)长度trainY约为0.8密耳

我目前的代码是:

sum([1 for n in x if label in trainY[n]])
Run Code Online (Sandbox Code Playgroud)

这是我的程序的性能瓶颈,我正在寻找一种方法来使它更快.我认为,我们可以在跳过循环x,只是做了矢量化仰视trainY喜欢trainY[x],但我无法得到的东西的工作.

谢谢.

Ffi*_*ydd 6

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

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.
Run Code Online (Sandbox Code Playgroud)