numpy - ndarray - 如何删除基于另一个数组的行 [英] numpy - ndarray - how to remove rows based on another array

查看:65
本文介绍了numpy - ndarray - 如何删除基于另一个数组的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从基于另一个数组的 ndarray 中删除行.例如:

I want to remove rows from a ndarray based on another array. for example:

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 的行的第一列将被删除

the first column of the rows with the values in k will be removed

推荐答案

您可以使用 np.in1dnk 的第一列之间创建匹配掩码,然后使用倒置掩码从 n 中选择不匹配的行,就像这样 -

You can use np.in1d to create a mask of matches between the first column of n and k and then use the inverted mask to select the non-matching rows off n, like so -

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

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

If the first column is already of int dtype, skip the .astype(int) conversion step.

样品运行 -

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 -

For peformance, if the first column is sorted, we can use np.searchsorted -

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

这篇关于numpy - ndarray - 如何删除基于另一个数组的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆