2015-11-13 49 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

相关问题