Tae
Tae

Reputation: 63

compare two different size array ( component of A is in B )

What I want to do is there are two different size array Let

A = [[1,3,1],[2,4,1],[3,3,1]]
B = [[1,3,1],[2,5,1],[2,3,1],[3,3,1],[5,5,1]]

Row of B may in A or not( [1,3,1], [3,3,1] is in A )

What I want to do from these arrays is compare two arrays in order to construct array "C" which is consist of the rows of B that is in A

C = [[1,3,1], [3,3,1]]

I have tried pandas.isin but I have failed.. Any idea would be very helpful

Upvotes: 1

Views: 82

Answers (3)

U13-Forward
U13-Forward

Reputation: 71580

Or with filter:

print(list(filter(lambda x: x in A.tolist(), B.tolist())))

Output:

[[1, 3, 1], [3, 3, 1]]

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can get common elements from both lists:

>>> A = [[1,3,1],[2,4,1],[3,3,1]]
>>> B = [[1,3,1],[2,5,1],[2,3,1],[3,3,1],[5,5,1]]
>>> print([data for data in A if data in B])
[[1, 3, 1], [3, 3, 1]]

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

Use set.intersection

Ex:

A = [[1,3,1],[2,4,1],[3,3,1]]
B = [[1,3,1],[2,5,1],[2,3,1],[3,3,1],[5,5,1]]

A = map(tuple, A)
B = map(tuple, B)
print(set(A).intersection(set(B)))

Output:

{(3, 3, 1), (1, 3, 1)}

Upvotes: 2

Related Questions