How can I “zip sort” parallel numpy arrays?

后端 未结 4 986
野趣味
野趣味 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:49

    Like @Peter Hansen's answer, this makes a copy of the arrays before it sorts them. But it is simple, does the main sort in-place, uses the second array for auxiliary sorting, and should be very fast:

    a = np.array([2, 3, 1])
    b = np.array([4, 6, 2])
    # combine, sort and break apart
    a, b = np.sort(np.array([a, b]))
    

    Update: The code above doesn't actually work, as pointed out in a comment. Below is some better code. This should be fairly efficient—e.g., it avoids explicitly making extra copies of the arrays. It's hard to say how efficient it will be, because the documentation doesn't give any details on the numpy.lexsort algorithm. But it should work pretty well, since this is exactly the job lexsort was written for.

    a = np.array([5, 3, 1])
    b = np.array([4, 6, 7])
    new_order = np.lexsort([b, a])
    a = a[new_order]
    b = b[new_order]
    print(a, b)
    # (array([1, 3, 5]), array([7, 6, 4]))
    

提交回复
热议问题