6

I haven't found this answer on SO, so I am sharing it here:

Question: How do you emulate sortrows functionality in matlab when there are multiple sorting keys? In matlab, this looks like e.g.:

sortrows(x,[3,-4])

which sorts first by the 3rd column and then by the second column.

If you were sorting by one column, you could use np.argsort to find the indices of that column, and apply those indices. But how do you do it for multiple columns?

2 Answers 2

5

The syntax is quite unwieldy and looks weird, but the cleanest thing to do is np.lexsort.

data = np.array([[3, 0, 0, .24],
                 [4, 1, 1, .41],
                 [2, 1, 1, .63],
                 [1, 1, 3, .38]]) #imagine rows of a spreadsheet
#now do sortrows(data,[3,-4])
ix = np.lexsort((data[:, 3][::-1], data[:, 2])) 
#this yields [0, 2, 1, 3]

#note that lexsort sorts first from the last row, so sort keys are in reverse order

data[ix]
0

EDIT2: as negative inicies in python have meaning, I think they should not be used to specify descending order for the column, therefore I used here an auxiliary Descending-object.

import numpy as np

class Descending:
    """ for np_sortrows: sort column in descending order """
    def __init__(self, column_index):
        self.column_index = column_index

    def __int__(self):  # when cast to integer
        return self.column_index


def np_sortrows(M, columns=None):
    """  sorting 2D matrix by rows
    :param M: 2D numpy array to be sorted by rows
    :param columns: None for all columns to be used,
                    iterable of indexes or Descending objects
    :return: returns sorted M
    """
    if len(M.shape) != 2:
        raise ValueError('M must be 2d numpy.array')
    if columns is None:  # no columns specified, use all in reversed order
        M_columns = tuple(M[:, c] for c in range(M.shape[1]-1, -1, -1))
    else:
        M_columns = []
        for c in columns:
            M_c = M[:, int(c)]
            if isinstance(c, Descending):
                M_columns.append(M_c[::-1])
            else:
                M_columns.append(M_c)
        M_columns.reverse()

    return M[np.lexsort(M_columns), :]

data = np.array([[3, 0, 0, .24],
                 [4, 1, 1, .41],
                 [2, 1, 3, .25],
                 [2, 1, 1, .63],
                 [1, 1, 3, .38]])

# third column is index 2, fourth column in reversed order at index 3    
print(np_sortrows(data, [2, Descending(3)]))
3
  • should be fixed now
    – karna7
    Feb 28, 2019 at 9:52
  • This is way more complicated than it needs to be. my_list_or_array[::-1] is standard in Python for getting the reverse of a list or array while maintaining its type. You can also use reversed, which is faster and easier to read. It returns an iterator. Sep 10, 2021 at 22:07
  • I do actualy use it in M_columns.append(M_c[::-1]) for the descending order
    – karna7
    Sep 28, 2021 at 5:53

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.