2017-03-31 89 views
0

我有一些非常大的數據集的問題。我需要找到一種堅實而快速的方式來查找/替換我的結構化數組中的條目。我正在尋找一個沒有循環所有條目的解決方案。我知道有C的快速解決方案,但我不知道如何在python的方法。我也想知道,爲了這個目的是否有一個numpy函數!PYTHON:檢查和編輯結構化數組中元素(如果存在)的最快方法是什麼?

我正在使用Python 2.7.13和numpy 1.12.1!

任務: 通過設置在切牙data_centrals名單從data_orphan找到孤兒哈羅依德孤兒到data_centrals的位置的所有位置。

import numpy as np 

data = Structured array: 
    class: ndarray 
    shape: (189258912,) 

dt = [('hostid', '<u8'), ('z_pos', '<f8'), ('x_pos', '<f8'), 
    ('y_pos', '<f8'), ('haloid', '<u8'), ('orphan', 'i1')] 

編輯:200名對象數據的子樣本可以下載here!它結構由DT給出:第一列 - >主機標識,第二 - >z_pos,等,它可以是複製/粘貼,因爲它是爲蟒殼或腳本...

您可以在下面找到設置職位的代碼。

問題:是否有巧妙的方法來搜索鹵素和設置位置,而不會循環所有條目data_orphan

data_centrals=data[np.where(data['haloid']==data['hostid'])] # (111958237,) 

data_orphans=data[np.where(data['orphan']==2)]    # (61870681,) 

a=0 
while a<len(data_orphans): 

    #check where in data_centrals the haloid of the orphan can be found 
    position=np.where(data_centrals['haloid']==data_orphans['haloid'][a]) 

    #find the position of data_orphan['haloid'][a] in data 
    position_data=np.where(data['hostid']==data_orphans['hostid'][a]) 

    #set the positions 
    data['x_pos'][int(position_data[0])]=data_centrals['x_pos'][int(position[0])]   
    data['y_pos'][int(position_data[0])]=data_centrals['y_pos'][int(position[0])]  
    data['z_pos'][int(position_data[0])]=data_centrals['z_pos'][int(position[0])] 

    a+=1 
+0

我懷疑'np.in1d'可以用於循環外的第一個'position' calc。 – hpaulj

+0

「data_orphans」和「data_central」相對於「data」的典型長度是多少? – hpaulj

+0

如果你堅持'np.where(data ['orphan'] == 2)',你不應該執行第二個'position_data''where'。 – hpaulj

回答

1

如果你的數據結構是普通的,無序列表或數組,那麼答案是否定的。它將花費線性時間O(n)來查找特定元素。如果列表/數組被排序,您可以在O(lg n)時間執行二進制搜索。您也可以考慮使用更好的搜索時間的平衡BST或Python字典等替代數據結構,但如果這種方法適合,則取決於數據結構。