laumrz
laumrz

Reputation: 23

Union of two matrices in Python

Is it posible to make de union between two matrices in python? I mean to have in one matrix all the elements from other two matrices without reapiting any of them. For example, if we have:

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

B = [[5,6],[7,8]]

The union would be C = [[1,2],[3,4],[5,6],[7,8]]

There is a numpy command for arrays: np.union1d but I cannot find any for matrices. I just have found np.concatenate and np.vstack but they write twice the repeated elements.

Upvotes: 2

Views: 2058

Answers (1)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

If I correctly understood your question, you can achieve using np.unique on the concated result of A and B, as below

import numpy as np
A = np.array([[1,2],[3,4],[5,6]])
B = np.array([[5,6],[7,8]])
np.unique(np.concatenate([A, B]), axis=0)

outputs

array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

or a bit more concise stacking would be np.unique(np.r_[A,B], axis=0)

Upvotes: 1

Related Questions