我有一组块状的元组:
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)标签最多只能在元组中出现一次,并且
2)元组的长度为1~ 5。
3)列表x的长度通常为7-50。
( 4) trainY长度约为0.8亿。
我现在要做的代码是:
sum([1 for n in x if label in trainY[n]])这是我的程序目前的一个性能瓶颈,我正在寻找一种方法,使它更快。我认为我们可以跳过x的循环,只需要进行矢量化查找,比如trainY[x],但是我找不到有用的东西。
谢谢。
发布于 2013-12-11 14:51:13
我认为在这种情况下使用计数器可能是一个很好的选择。
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.发布于 2013-12-11 14:58:36
您可以在使用列表理解来处理数组之后使用np.in1d:
trainY = np.array([i for j in trainY for i in j])
ans = np.in1d(trainY, 'php').sum()
# 2发布于 2013-12-11 14:48:00
考虑建立一本表格字典:
{'string1': (1,2,5),
'string2': (3,4,5),
...
}对于每一个词,保存它在元组中出现的索引的排序列表。希望这有意义..。
https://stackoverflow.com/questions/20521873
复制相似问题