Reputation: 327
I have one numpy array =
[1,6,7,9,3,5]
and a second numpy array =
[3,5,8,9,2]
I would like to merge these two arrays together:
[1,6,7,9,3,5,3,5,8,9,2]
and then remove the duplicates in the numpy array to get :
[1,6,7,9,3,5,8,2]
I would like to keep as much of array one as possible and take out elements of array two, that don't appear in array one, and append these.
I am not sure if it makes more sense to:
I have tried using various loops but these appear to work mostly for lists, I have also tried using set()
but this orders the numpy
array, I would like to keep the random order form.
Upvotes: 3
Views: 8506
Reputation: 6509
Here is slightly different way to do it also:
z = np.concatenate([x, y[~np.isin(y,x)])
Upvotes: 4
Reputation: 51155
To join the two arrays, you can simply use np.concatenate
Removing duplicates while preserving order is a bit tricky, because normally np.unique
also sorts, but you can use return_index
then sort to get around this:
In [61]: x
Out[61]: array([1, 6, 7, 9, 3, 5])
In [62]: y
Out[62]: array([3, 5, 8, 9, 2])
In [63]: z = np.concatenate((x, y))
In [64]: z
Out[64]: array([1, 6, 7, 9, 3, 5, 3, 5, 8, 9, 2])
In [65]: _, i = np.unique(z, return_index=True)
In [66]: z[np.sort(i)]
Out[66]: array([1, 6, 7, 9, 3, 5, 8, 2])
Upvotes: 11