2017-04-16 75 views
0

我正在創建一個2xn數組的元組列表,其中第一行是一個ID,第二行是這個ID組的分配。我想創建一個組織分配給他們小組的ID的列表。從二維數組創建元組列表

例如:

array([[ 0., 1., 2., 3., 4., 5., 6.], 
     [ 1., 2., 1., 2., 2., 1., 1.]) 

在上述示例中,ID 0分配給組1,ID 1至組2,依此類推。輸出列表看起來像:

a=[(0,2,5,6),(1,3,4)] 

沒有人有任何創造性的,快速的方法來做到這一點?

謝謝!

回答

1

標準(對不起,沒有創意 - 但相當快)numpy的方式將是一個間接的排序:

import numpy as np 

data = np.array([[ 0., 1., 2., 3., 4., 5., 6.], 
       [ 1., 2., 1., 2., 2., 1., 1.]]) 

index = np.argsort(data[1], kind='mergesort') # mergesort is a bit 
               # slower than the default 
               # algorithm but is stable, 
               # i.e. if there's a tie 
               # it will preserve order 
# use the index to sort both parts of data 
sorted = data[:, index] 
# the group labels are now in blocks, we can detect the boundaries by 
# shifting by one and looking for mismatch 
split_points = np.where(sorted[1, 1:] != sorted[1, :-1])[0] + 1 

# could convert to int dtype here if desired 
result = map(tuple, np.split(sorted[0], split_points)) 
# That's Python 2. In Python 3 you'd have to explicitly convert to list: 
# result = list(result) 
print(result) 

打印:

[(0.0, 2.0, 5.0, 6.0), (1.0, 3.0, 4.0)]