2

I have two numpy arrays:

lst = np.array([8, 1, 6, 9, 2])

arr = np.array([[[  6, 455],
    [  8, 106],
    [  1, 953],
    [  2, 725],
    [  9, 427]],

   [[  2, 427],
    [  8, 953],
    [  1, 106],
    [  9, 455],
    [  6, 725]]])

Note that arr[0,:,0] and arr[1,:,0] are both permutations of lst.

I want to sort arr such that both arr[0,:,0] and arr[1,:,0] are in the same order as lst (and the rows are correctly sorted). In other words, I want the following outcome:

ans = np.array([[[  8, 106],
        [  1, 953],
        [  6, 455],
        [  9, 427],
        [  2, 725]],
       [[  8, 953],
        [  1, 106],
        [  6, 725],
        [  9, 455],
        [  2, 427]]])

I can get my desired outcome using list comprehension, but I'm looking for a more efficient solution. Can anyone help me? Thank you.

1 Answer 1

1

You can map the indexes then pick accordingly

# for arr[0,:,0]

mapping = dict(zip(arr[0,:,0], np.arange(arr[0,:,0].shape[0])))

vfunc = np.vectorize(mapping.__getitem__)
new_index = vfunc(lst)

print(arr[0, new_index, :])

# array([[  8, 106],
#        [  1, 953],
#        [  6, 455],
#        [  9, 427],
#        [  2, 725]])
Sign up to request clarification or add additional context in comments.

2 Comments

So do you wrap this with a loop (for the other subarrays)? Is there a built-in numpy method that deals with this in one go?
You can try np. vectorize but it is essential for loop under the hood but gives a clear syntax. If speed is not concened.

Your Answer

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