开发者

Equivalent of 'ismember' from Matlab in Python? [duplicate]

开发者 https://www.devze.com 2023-01-18 06:52 出处:网络
This question already has answers here: Python equivalent of MATLAB's "ismember" function
This question already has answers here: Python equivalent of MATLAB's "ismember" function (5 answers) 开发者_JAVA技巧 Closed 2 years ago.

I am trying to perform a comparison between the rows of two matrices A and B with the same number of columns.

In matlab the command ismember(a, b, 'rows') returns a vector containing 1 where the rows of A are also rows of B and 0 otherwise, and also returns the highest index in B for each element in A that is a member of B.

[tf, index] = ismember(A, B, 'rows');

Is there an equivalent function in python? Any ideas how to do it?


you can get your vector as

same_rows = [a == b for a,b in zip(A, B)]

Note that this will yield True and False instead of 1 and 0 but bool is subclassed from int and True == 1 and False == 0.

to get the max row where this occurs, you can just use

max_row = next(i for i, row in enumerate(reversed(same_rows)) if row == True)

If you want the number of rows that they have in common, you can just use

same_count == sum(same_rows)

Note that this is all for python and assumes that matrices are lists of lists or tuples or tuples of lists or tuples. HTH.


The ismember library can be helpful.

pip install ismember

Example:

# Import library
from ismember import ismember

# Example with random matrices
a_vec = np.random.randint(0,10,(5,8))
b_vec = np.random.randint(0,10,(5,10))

# Row-wise comparison
Iloc, idx = ismember(a_vec, b_vec, 'rows')

# These should all be True
for i in np.arange(0,a_vec.shape[0]):
    np.all(a_vec[i,Iloc[i]]==b_vec[i,idx[i]])
0

精彩评论

暂无评论...
验证码 换一张
取 消