2015-11-13 57 views
2

我想找到最佳的方式來將具有類似ID的'行'分組。最快的方法,以一個非常大的numpy陣列的ID分組

我最好的猜測: np.array([test[test[:,0] == ID] for ID in List_IDs])

結果:陣列

的數組的數組
[ array([['ID_1', 'col1','col2',...,'coln'], 
     ['ID_1', 'col1','col2',...,'coln'],..., 
     ['ID_1', 'col1','col2',...,'coln']],dtype='|S32') 
array([['ID_2', 'col1','col2',...,'coln'], 
     ['ID_2', 'col1','col2',...,'coln'],..., 
     ['ID_2', 'col1','col2',...,'coln']],dtype='|S32') 
.... 
array([['ID_k', 'col1','col2',...,'coln'], 
     ['ID_k', 'col1','col2',...,'coln'],..., 
     ['ID_K', 'col1','col2',...,'coln']],dtype='|S32')] 

任何人都可以提出一些可以更有效率?

提醒:test陣列是巨大的。 '行'沒有訂購

+6

有你看着'pandas',這有專門爲這個 – EdChum

+0

「龐大」的是'groupby'方法一個相對術語。你可以再詳細一點嗎?一百萬行?一億? –

+0

@WarrenWeckesser我現在正在與30萬。更多預計的數據 – belas

回答

2

我假設List_IDs是來自第一列的所有唯一ID的列表。有了這樣的假設,這裏有一個基於NumPy的解決方案 -

# Sort input array test w.r.t. first column that are IDs 
test_sorted = test[test[:,0].argsort()] 

# Convert the string IDs to numeric IDs 
_,numeric_ID = np.unique(test_sorted[:,0],return_inverse=True) 

# Get the indices where shifts (IDs change) occur 
_,cut_idx = np.unique(numeric_ID,return_index=True) 

# Use the indices to split the input array into sub-arrays with common IDs 
out = np.split(test_sorted,cut_idx)[1:] 

採樣運行 -

In [305]: test 
Out[305]: 
array([['A', 'A', 'B', 'E', 'A'], 
     ['B', 'E', 'A', 'E', 'B'], 
     ['C', 'D', 'D', 'A', 'C'], 
     ['B', 'D', 'A', 'C', 'A'], 
     ['B', 'A', 'E', 'A', 'E'], 
     ['C', 'D', 'C', 'E', 'D']], 
     dtype='|S32') 

In [306]: test_sorted 
Out[306]: 
array([['A', 'A', 'B', 'E', 'A'], 
     ['B', 'E', 'A', 'E', 'B'], 
     ['B', 'D', 'A', 'C', 'A'], 
     ['B', 'A', 'E', 'A', 'E'], 
     ['C', 'D', 'D', 'A', 'C'], 
     ['C', 'D', 'C', 'E', 'D']], 
     dtype='|S32') 

In [307]: out 
Out[307]: 
[array([['A', 'A', 'B', 'E', 'A']], 
     dtype='|S32'), array([['B', 'E', 'A', 'E', 'B'], 
     ['B', 'D', 'A', 'C', 'A'], 
     ['B', 'A', 'E', 'A', 'E']], 
     dtype='|S32'), array([['C', 'D', 'D', 'A', 'C'], 
     ['C', 'D', 'C', 'E', 'D']], 
     dtype='|S32')] 
+0

謝謝。你的解決方案比我的更快。你能簡單解釋爲什麼這個解決方案更快嗎?我應該得到的關鍵洞察是什麼? – belas

+0

@belas爲什麼這個解決方案比你的解決方案更快?我會說NumPy funcs通常比用Python工具循環更有效率。特別是對於這個解決方案,我們使用'np.unique'將字符串轉換爲數字ID,一旦我們有了數字ID,我們就進入了NumPy領域,因爲它易於操作和使用它們。這裏唯一的瓶頸是分裂的最後一步,因爲存儲NumPy數組列表並不是一個真正有效的方法。 – Divakar

+0

@belas因此,外賣消息將盡可能使用NumPy funcs並保持它們的形狀。我只是回答了一個處理字符串的非常類似的問題,請看一下 - http://stackoverflow.com/a/33698907/3293881 – Divakar

相關問題