Combine and remove duplicate element from arrays
I am calculating an array of indices in each iteration of the loop, and then I want to remove duplicate items and concatenate the calculated array into the previous one. For example, the first iteration gives me this array:
array([ 1, 6, 56, 120, 162, 170, 176, 179, 197, 204])
and second:
array([ 29, 31, 56, 104, 162, 170, 176, 179, 197, 204])
etc. How can i do this?
+3
source to share
2 answers
you can concatenate the arrays first with numpy.concatenate
then usenp.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]
+5
source to share
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])
+1
source to share