0

For example I have

array1 = np.array([[3,2,1],[2,1,3]])

array2 = np.array([[4,5,6],[7,8,9]])

I sort array1 to get [[1,2,3],[1,2,3]] and I want to sort array2 to get [[6,5,4],[8,7,9]]

What I tried to do is the following:

index = np.argsort(array1,axis = 1)

array2[index]

But it doesnt work, any help is very much appreciated

1
  • so sort function uses a parameter called key read about it Commented May 22, 2020 at 5:42

2 Answers 2

1

np.argsort is the right direction. Use the following code:

array1 = np.array([[3,2,1],[2,1,3]])
array2 = np.array([[4,5,6],[7,8,9]])

def order_by(arr1, arr2):
    order = np.argsort(arr1)
    return [arr2[o] for o in order ]

[order_by(a1, a2) for (a1, a2) in zip(array1, array2) ]

The result is:

[[6, 5, 4], [8, 7, 9]]
Sign up to request clarification or add additional context in comments.

Comments

0

Below is my implementation without using any in bulit methods. Time Complexity is O(n^2)

def weird_sort(lst1,lst2):
    sorted_lst2=[]
    sorted_lst1=[]
    lst3=[i for i in lst1]
    while len(lst1)>0:
        _min=lst1[0]

        for i in range(1,len(lst1)):
            if lst1[i] <_min:_min=lst1[i]
        sorted_lst2.append(lst2[lst3.index(_min)])
        lst1.remove(_min)
        sorted_lst1.append(_min)

    return sorted_lst1,sorted_lst2

This function can be called as :

import numpy as np
array1 = np.array([[3,2,1],[2,1,3]])
array2 = np.array([[4,5,6],[7,8,9]])

for i,j in zip(array1,array2):
    print(list(weird_sort(list(i),list(j))))

Output is as required:

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

Edit : Modify the function return a bit to get the output in whatever the format you need. Mine is not exactly what you wanted but this do can do the trick.

Hope this helps.

1 Comment

Yes, this was helpful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.