numpy - ndarray - 如何基于另一个数组删除行

3
我希望你能够根据另一个数组从ndarray中删除行。 例如:
k = [1,3,99]

n = [
  [1,'a']
  [2,'b']
  [3,'c']
  [4,'c']
  [.....]
  [99, 'a']
  [100,'e']
]

预期结果:

out = [
  [2,'b']
  [4,'c']
  [.....]
  [100,'e']
]

值为k的行的第一列将被移除。

2个回答

1
您可以使用 np.in1d 来创建一个匹配第一列 nk 之间的掩码,然后使用反转的掩码来选择 n 中不匹配的行,就像这样 -
n[~np.in1d(n[:,0].astype(int), k)]

如果第一列已经是int数据类型,则跳过.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')

为了提高性能,如果第一列已经排序好,我们可以使用np.searchsorted函数 -

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

搜索排序解决方案只删除了与k匹配的第一个元素,其他两行没有被删除。 - Wenhui
@Wenhui 第一列的 n 是否已排序?如果是,则尝试使用 mask[np.searchsorted(n[:,0].astype(int), k)] = 0 - Divakar
@Wenhui 这个回答解决了你的问题吗? - 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接