How can I “zip sort” parallel numpy arrays?

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

    Here's an approach that creates no intermediate Python lists, though it does require a NumPy "record array" to use for the sorting. If your two input arrays are actually related (like columns in a spreadsheet) then this might open up an advantageous way of dealing with your data in general, rather than keeping two distinct arrays around all the time, in which case you'd already have a record array and your original problem would be answered merely by calling sort() on your array.

    This does an in-place sort after packing both arrays into a record array:

    >>> from numpy import array, rec
    >>> a = array([2, 3, 1])
    >>> b = array([4, 6, 7])
    >>> c = rec.fromarrays([a, b])
    >>> c.sort()
    >>> c.f1   # fromarrays adds field names beginning with f0 automatically
    array([7, 4, 6])
    

    Edited to use rec.fromarrays() for simplicity, skip redundant dtype, use default sort key, use default field names instead of specifying (based on this example).

提交回复
热议问题