等价于Matlab中的'ismember'吗? [英] Equivalent of 'ismember' from Matlab in Python?
问题描述
我正在尝试对列数相同的两个矩阵A和B的行进行比较.
I am trying to perform a comparison between the rows of two matrices A and B with the same number of columns.
在matlab中,命令ismember(a, b, 'rows')
返回一个包含1的向量,其中A的行也是B的行,否则返回0,并且还返回B中成员B中元素A中每个元素在B中的最高索引. /p>
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');
python中是否有等效的功能?有什么想法怎么做吗?
Is there an equivalent function in python? Any ideas how to do it?
推荐答案
您可以将向量设为
same_rows = [a == b for a,b in zip(A, B)]
请注意,这将产生True
和False
而不是1和0,但是bool
是int
和True == 1
和False == 0
的子类.
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)
请注意,这全部用于python,并假定矩阵是列表或元组的列表或列表或元组的元组. HTH.
Note that this is all for python and assumes that matrices are lists of lists or tuples or tuples of lists or tuples. HTH.
这篇关于等价于Matlab中的'ismember'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!