Sorting an array with respect to an another array

Viewed 178

I am using some datas in my program were I have some sorting issue which takes longer time for me. So I have mentioned an example situation here for which I would like to get a solution.

import numpy as np 
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = np.array([[4,5,6,7],[7,8,9,4],[1,2,3,2]])
# Need to apply some sort function
C = sort(B[:,0:3] to be sorted with respect to A)
print(C)

I have two numpy arrays were I would like the first 3 columns of array B to be sorted with respect to array A.

And I want the output of C as

[[1,2,3,2],[4,5,6,7],[7,8,9,4]]

Is there any numpy method or any other python libraries which could do this.

Looking forward for some answers

Regards

Aadithya

1 Answers

This only works when using the first column :

_, indexer, _ = np.intersect1d(B[:,:1], A[:,:1], return_indices=True)

B[indexer]

array([[1, 2, 3, 2],
   [4, 5, 6, 7],
   [7, 8, 9, 4]])

Apparently, the above solution works only if the values are unique (Thanks @AadithyaSaathya.

If we are to use all of A, we could use itertools' product function :

from itertools import product
indexer = [B[0] 
           for A,B 
           in
           product(enumerate(A), enumerate(B[:,:3]))
           if np.all(np.equal(A[-1], B[-1]))]

B[indexer]


array([[1, 2, 3, 2],
       [4, 5, 6, 7],
       [7, 8, 9, 4]])
Related