2

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.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
laumrz
  • 23
  • 4
  • It's not a "proper" union, but you can work the result out with a simple list-loop: `C = A + [ x for x in B if x not in A ]` – Kingsley Jun 16 '20 at 07:01

1 Answers1

1

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)

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208