How can I “zip sort” parallel numpy arrays?

后端 未结 4 1010
野趣味
野趣味 2020-11-28 04:12

If I have two parallel lists and want to sort them by the order of the elements in the first, it\'s very easy:

>>> a = [2, 3, 1]
>>> b = [4         


        
4条回答
  •  甜味超标
    2020-11-28 04:58

    This might the simplest and most general way to do what you want. (I used three arrays here, but this will work on arrays of any shape, whether two columns or two hundred).

    import numpy as NP
    fnx = lambda : NP.random.randint(0, 10, 6)
    a, b, c = fnx(), fnx(), fnx()
    abc = NP.column_stack((a, b, c))
    keys = (abc[:,0], abc[:,1])          # sort on 2nd column, resolve ties using 1st col
    indices = NP.lexsort(keys)        # create index array
    ab_sorted = NP.take(abc, indices, axis=0)
    

    One quirk w/ lexsort is that you have to specify the keys in reverse order, i.e., put your primary key second and your secondary key first. In my example, i want to sort using the 2nd column as the primary key so i list it second; the 1st column resolves ties only, but it is listed first).

提交回复
热议问题