Python numpy filter two-dimensional array by condition

前端 未结 4 1720
半阙折子戏
半阙折子戏 2020-12-19 03:26

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

4条回答
  •  离开以前
    2020-12-19 04:20

    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.

提交回复
热议问题