Python numpy filter two-dimensional array by condition

前端 未结 4 1703
半阙折子戏
半阙折子戏 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:04

    In this case where the len(filter) is sufficiently smaller than a[:,1], np.in1d does an iterative version of

    mask = (a[:,1,None] == filter[None,:]).any(axis=1)
    a[mask,:]
    

    It does (adapting the in1d code):

    In [1301]: arr1=a[:,1];arr2=np.array(filter)
    In [1302]: mask=np.zeros(len(arr1),dtype=np.bool)
    In [1303]: for i in arr2:
          ...:     mask |= (arr1==i)
    In [1304]: mask
    Out[1304]: array([ True, False,  True, False], dtype=bool)
    

    With more items in filter is would build its search around unique, concatenate and argsort, looking for duplicates.

    So it's convenience hides a fair amount of complexity.

提交回复
热议问题