7

从以下数组:

test = np.array([[1,2,'a'],[4,5,6],[7,'a',9],[10,11,12]])

如何删除包含 'a' 的行?预期结果 :

array([[ 4,  5,  6],
   [10, 11, 12]])
4

3 回答 3

11

注意,numpy支持向量化比较:

>>> test
array([[1, 2, 'a'],
       [4, 5, 6],
       [7, 'a', 9],
       [10, 11, 12]], dtype=object)
>>> test == 'a'
array([[False, False,  True],
       [False, False, False],
       [False,  True, False],
       [False, False, False]], dtype=bool)

现在,您想要所有等于的'a'

>>> (test != 'a').all(axis=1)
array([False,  True, False,  True], dtype=bool)

因此,只需选择带有掩码的行:

>>> row_mask = (test != 'a').all(axis=1)
>>> test[row_mask,:]
array([[4, 5, 6],
       [10, 11, 12]], dtype=object)
于 2017-12-14T17:45:03.313 回答
3

还有,可能是这样吗?(灵感来自我的另一个答案

In [100]: mask = ~(test == 'a')

In [101]: mask
Out[101]: 
array([[ True,  True, False],
       [ True,  True,  True],
       [ True, False,  True],
       [ True,  True,  True]], dtype=bool)

In [102]: test[np.all(mask, axis=1), :]
Out[102]: 
array([['4', '5', '6'],
       ['10', '11', '12']],
      dtype='<U21')

但是,请注意,这里我们不会 从原始数组中删除任何行。我们只是切掉没有字母的行a

于 2017-12-14T17:54:56.987 回答
2

总结一下,有几种可能的方法,例如:

test[np.all(test != 'a', axis=1), :]

或者

test[(test != 'a').all(axis=1)]
于 2017-12-14T18:04:19.453 回答