How can I implement matlabs ``ismember()`` command in Python?

后端 未结 6 2300
星月不相逢
星月不相逢 2020-12-19 22:59

here is my problem: I would like to create a boolean matrix B that contains True everywhere that matrix A has a value contained in vector v. One inconvenient so

6条回答
  •  独厮守ぢ
    2020-12-19 23:26

    Alas, setmember1d as it exists in numpy is broken when either array has duplicated elements (as A does here). Download this version, call it e.g sem.py somewhere on your sys.path, add to it a first line import numpy as nm, and THEN this finally works:

    >>> import sem
    >>> print sem.setmember1d(A.reshape(A.size), v).reshape(A.shape)
    [[False True True]
     [True True False]
     [True False False]]
    

    Note the difference wrt @Aants' similar answer: this version has the second row of the resulting bool array correct, while his version (using the setmember1d that comes as part of numpy) incorrectly has the second row as all Trues.

提交回复
热议问题