2017-04-27 101 views

回答

1

可以使用np.in1d创建之间的匹配的掩模的nk,然后将第一列中使用反转掩模来选择非匹配的行断n,像这样 -

n[~np.in1d(n[:,0].astype(int), k)] 

如果第一列已经是int dtype,则跳过.astype(int)转换步骤。

采样运行 -

In [41]: n 
Out[41]: 
array([['1', 'a'], 
     ['2', 'b'], 
     ['3', 'c'], 
     ['4', 'c'], 
     ['99', 'a'], 
     ['100', 'e']], 
     dtype='|S21') 

In [42]: k 
Out[42]: [1, 3, 99] 

In [43]: n[~np.in1d(n[:,0].astype(int), k)] 
Out[43]: 
array([['2', 'b'], 
     ['4', 'c'], 
     ['100', 'e']], 
     dtype='|S21') 

对于peformance,如果第一列进行排序,我们可以使用np.searchsorted -

mask = np.ones(n.shape[0],dtype=bool) 
mask[np.searchsorted(n[:,0], k)] = 0 
out = n[mask] 
+0

谢谢!这是伟大的:) – Wenhui

+0

的searchsorted解决方案只是删除k的第一个匹配元素,其他两行不被删除 – Wenhui

+0

@Wenhui是第一列'N'排序?如果是,尝试用'掩模[np.searchsorted(N [:,0] .astype(INT)中,k)] = 0'。 – Divakar

0

如果你的数据结构列表,请在下面找到简单的解决方案,但是你可以通过list()方法转换成列表。

def check(list): 
k=[1,3,99] 
if(list[0] not in k): 
    return list 

final_list = map(check,n) 
final_list = final_list.remove(None) 
print final_list