Python newbie here, I have read Filter rows of a numpy array? and the doc but still can\'t figure out how to code it the python way.
Example array I have: (the real
A somewhat elaborate pure numpy
vectorized solution:
>>> import numpy
>>> a = numpy.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']])
>>> filter = numpy.array(['a','c'])
>>> a[(a[:,1,None] == filter[None,:]).any(axis=1)]
array([['2', 'a'],
['4', 'c']],
dtype='|S21')
None
in the index creates a singleton dimension, therefore we can compare the column of a
and the row of filter
, and then reduce the resulting boolean array
>>> a[:,1,None] == filter[None,:]
array([[ True, False],
[False, False],
[False, True],
[False, False]], dtype=bool)
over the second dimension with any
.