Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain order when taking unique rows in a NumPy array

I have three 2D arrays a1, a2, and a3

In [165]: a1
Out[165]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

In [166]: a2
Out[166]: 
array([[ 9, 10, 11],
       [15, 16, 17],
       [18, 19, 20]])

In [167]: a3 
Out[167]: 
array([[6, 7, 8],
       [4, 5, 5]])

And I stacked these arrays into a single array:

In [168]: stacked = np.vstack((a1, a2, a3))

In [170]: stacked 
Out[170]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [ 9, 10, 11],
       [15, 16, 17],
       [18, 19, 20],
       [ 6,  7,  8],
       [ 4,  5,  5]])

Now, I want to get rid of the duplicate rows. So, numpy.unique does the job.

In [169]: np.unique(stacked, axis=0)
Out[169]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 4,  5,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [15, 16, 17],
       [18, 19, 20]])

However, there is one issue here. The original order is lost when taking the unique rows. How can I retain the original ordering and still take the unique rows?

So, the expected output should be:

array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [15, 16, 17],
       [18, 19, 20],
       [ 4,  5,  5]])
like image 586
kmario23 Avatar asked Jan 11 '19 04:01

kmario23


People also ask

Does NP save Preserve orders?

save , use np. savez . Note that the order is not preserved. If you do need to preserve order, you might consider using pickle instead.

How does NP unique sort?

The numpy. unique function allows to return the counts of unique elements if return_counts is True . Now the returned tuple consists of two arrays one containing the unique elements and the 2nd one containing a count array, both are sorted by the unique elements.

Which of the following is a possible way to find unique rows in NumPy array?

To find unique rows in a NumPy array we are using numpy. unique() function of NumPy library.

How do I arrange in NumPy ascending order?

Use numpy. sort() function to sort the elements of NumPy array in an ordered sequence. The parameter arr is mandatory. If you execute this function on a one-dimensional array, it will return a one-dimensional sorted array containing elements in ascending order.


1 Answers

Using return_index

_,idx=np.unique(stacked, axis=0,return_index=True)

stacked[np.sort(idx)]
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [15, 16, 17],
       [18, 19, 20],
       [ 4,  5,  5]])
like image 153
BENY Avatar answered Sep 21 '22 03:09

BENY