2011-01-07 80 views
2

我有一個由7列和〜900k行組成的數據集。所有列都是非唯一的,所有值都是整數。對於過濾什麼是在Python中過濾整數表的最快方法?

兩個重要條件:

  • 我嚴格希望看到哪些值有在一列當我申請的休息條件。
  • 對於輸出我只對不同的值感興趣。

此處作爲一例是用於基準測試性能的SQL查詢:

SELECT DISTINCT 
col_2 
FROM dataset 
WHERE 
c_1 in (1,9,5,6,8,18,14,7,15) AND 
c_3 in (1) AND 
c_4 in (61) AND 
c_5 in (3) AND 
c_6 in (0) AND 
c_7 in (0) 

我嘗試的第一個方法是SQL與使用SQLite指數,它並沒有做太糟糕了,但作爲過濾器回報很多,表現下降。

然後我在Python中嘗試了普通的香草列表解析。性能比在SQL情況下差一點。

有沒有更好的方法來做到這一點?我在朝numpy的方向思考,也許使用比列表和SQL表更高效的數據結構?

我對速度和性能非常感興趣,效率更低。

歡迎任何建議!

+0

聽起來確實像一個數據庫是不是最好的方式來存儲這個。你有沒有想過使用[Cython](http://cython.org/)?當您添加靜態類型註釋時,存儲效率會更高(您可以使用機器字)並且速度相當快(出於同樣的原因)。 – delnan 2011-01-07 09:44:09

+0

當你試圖SQLite是你的數據庫在內存或磁盤?如果它是在一個文件上嘗試使用`:memory:`,使用sqlite的內存數據庫通常比Python這樣的任務快得多。你的所有專欄索引? – 2011-01-07 09:47:52

+1

我同意DB解決方案在這裏並不是最好的選擇,我更多地將它用作基準測試工具。我正在做一個c-extension作爲一個實驗。然而,我想知道在Numpy中是否有一種有效的方式來做到這一點,對我來說這是一個未知的領域。 – c00kiemonster 2011-01-07 09:49:29

回答

2

以下是關於你所說的每列大約20個不同的值,除了一個是400.如果內存和加載時間不是一個擔心,那麼我建議爲每列的值創建集。

下面是生成一個示例數據集的東西。

#!/usr/bin/python 
from random import sample, choice 
from cPickle import dump 

# Generate sample dataset 
value_ceiling = 1000 
dataset_size = 900000 
dataset_filename = 'dataset.pkl' 

# number of distinct values per column 
col_distrib = [400,20,20,20,20,20,20] 

col_values = [ sample(xrange(value_ceiling),x) for x in col_distrib ] 

dataset = [] 
for _ in xrange(dataset_size): 
    dataset.append(tuple([ choice(x) for x in col_values ])) 

dump(dataset,open(dataset_filename,'wb')) 

下面是加載數據集並創建每列每個值的查找集,搜索方法和樣本搜索的創建。

#/usr/bin/python 

from random import sample, choice 
from cPickle import load 

dataset_filename = 'dataset.pkl' 

class DataSearch(object): 
    def __init__(self,filename): 
    self.data = load(open(filename,'rb')) 
    self.col_sets = [ dict() for x in self.data[0] ] 
    self.process_data() 
    def process_data(self): 
    for row in self.data: 
     for i,v in enumerate(row): 
     self.col_sets[i].setdefault(v,set()).add(row) 
    def search(self,*args): 
    # args are integers, sequences of integers, or None in related column positions. 
    results = [] 
    for i,v in enumerate(args): 
     if v is None: 
     continue 
     elif isinstance(v,int): 
     results.append(self.col_sets[i].get(v,set())) 
     else: # sequence 
     r = [ self.col_sets[i].get(x,set()) for x in v ] 
     r = reduce(set.union,r[1:],r[0]) 
     results.append(r) 
    # 
    results.sort(key=len) 
    results = reduce(set.intersection,results[1:],results[0]) 
    return results 
    def sample_search(self,*args): 
    search = [] 
    for i,v in enumerate(args): 
     if v is None: 
     search.append(None) 
     else: 
     search.append(sample(self.col_sets[i].keys(),v)) 
    return search 

d = DataSearch(dataset_filename) 

,並用它:

>>> d.search(*d.sample_search(1,1,1,5)) 
set([(117, 557, 273, 437, 639, 981, 587), (117, 557, 273, 170, 53, 640, 467), (117, 557, 273, 584, 459, 127, 649)]) 
>>> d.search(*d.sample_search(1,1,1,1)) 
set([]) 
>>> d.search(*d.sample_search(10,None,1,1,1,1)) 
set([(801, 334, 414, 283, 107, 990, 221)]) 
>>> d.search(*d.sample_search(10,None,1,1,1,1)) 
set([]) 
>>> d.search(*d.sample_search(10,None,1,1,1,1)) 
set([(193, 307, 547, 549, 901, 940, 343)]) 
>>> import timeit 
>>> timeit.Timer('d.search(*d.sample_search(10,None,1,1,1,1))','from __main__ import d').timeit(100) 
1.787431001663208 

1.8秒做100個搜索速度不夠快?

0

這就是我想出了:

513 $ cat filtarray.py 
#!/usr/bin/python2 
# 
import numpy 
import itertools 

a = numpy.fromiter(xrange(7*900000), int) 
a.shape = (900000,7) 
# stuff a known match 
a[33][0] = 18 
a[33][2] = 1 
a[33][3] = 61 
# filter it, and make list, but that is not strictly necessary. 
res = list(itertools.ifilter(lambda r: r[0] in (1,9,5,6,8,18,14,7,15) and r[2] == 1 and r[3] == 61, a)) 
print res 

它運行在Intel E8400:

512 $ time python filtarray.py 
[array([ 18, 232, 1, 61, 235, 236, 237])] 
python filtarray.py 5.36s user 0.05s system 99% cpu 5.418 total 

是快一點嗎?

0

這是一個numpy版本,大約需要1秒。

x = numpy.random.randint(0, 100, (7, 900000)) 

def filter(data, filters): 
    indices = [] 
    for i, filter in enumerate(filters): 
     indices.append(numpy.any([data[i] == x for x in filter], 0)) 

    indices = numpy.all(indices, 0) 
    return data[indices] 

# Usage: 
filter(x, [(1,9,5,6,8,18,14,7,15), (1,), (61,), (3,), (0,), (0,)]) 

%timeit filter(x, [(1,9,5,6,8,18,14,7,15), (1,), (61,), (3,), (0,), (0,)]) 
1 loops, best of 3: 903 ms per loop 
相關問題