Dalek
Dalek

Reputation: 4318

concatenate and remove duplicate element from numpy arrays

I compute an array of indices in each iteration of a loop and then I want to remove the duplicate elements and concatenate the computed array to the previous one. For example the first iteration gives me this array:

array([  1,   6,  56, 120, 162, 170, 176, 179, 197, 204])

and the second one:

array([ 29,  31,  56, 104, 162, 170, 176, 179, 197, 204]) 

and so on. How could I do it?

Upvotes: 13

Views: 15963

Answers (3)

Manuel F.
Manuel F.

Reputation: 255

numpy.union1d is the one-numpy function you're looking for (in this case).

import numpy as np
print( np.union1d([ 1, 6,56,120,162,170,176,179,197,204],\
                  [29,31,56,104,162,170,176,179,197,204]) )
# result
[  1   6  29  31  56 104 120 162 170 176 179 197 204]

Upvotes: 3

Kasravnd
Kasravnd

Reputation: 107297

you can concatenate arrays first with numpy.concatenate then use np.unique

import numpy as np
a=np.array([1,6,56,120,162,170,176,179,197,204])
b=np.array([29,31,56,104,162,170,176,179,197,204])
new_array = np.unique(np.concatenate((a,b),0))

print new_array

result:

[  1   6  29  31  56 104 120 162 170 176 179 197 204]

Upvotes: 19

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250981

You can use numpy.concatenate and numpy.unique:

In [81]: arr = np.array([  1,   6,  56, 120, 162, 170, 176, 179, 197, 204])

In [82]: arr = np.unique(np.concatenate((arr, np.array([ 29,  31,  56, 104, 162, 170, 176, 179, 197, 204]))))

In [83]: arr
Out[83]: array([  1,   6,  29,  31,  56, 104, 120, 162, 170, 176, 179, 197, 204])

Upvotes: 2

Related Questions