14

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?

2

3 Answers 3

20

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Looks like you beat me to it.
3

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]

1 Comment

Seems a better answer than the currently selected one.
2

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.