![](/img/trans.png)
[英]Is there a faster way I can count the number of occurrences of a number in a list?
[英]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.