1

I want to sort 2d array column-wise consequently, so if the values in one column are equal then sorting is performed by next column. For example array

[[1, 0, 4, 2, 3]
 [0, 1, 5, 7, 4]
 [0, 0, 6, 1, 0]]

must be sorted as

[[0, 0, 6, 1, 0]
 [0, 1, 5, 7, 4]
 [1, 0, 4, 2, 3]]

So rows must not be changed, only their order. How can I do that?

Nourless
  • 729
  • 1
  • 5
  • 18
  • It can help? [How to sort 2d array by row in python?](https://stackoverflow.com/questions/2173797/how-to-sort-2d-array-by-row-in-python/2173873) – magicarm22 Jul 12 '21 at 09:44
  • Can you please elaborate on how the sorting is done? it's very unclear. – Guy Jul 12 '21 at 09:47
  • @magicarm22, no, as far as I can see there is no answer to my question and moreover I talk about numpy and want to use its functions whereas it is lists that are discussed in that topic – Nourless Jul 12 '21 at 09:49
  • @Guy, well we sort rows by the first column. If values in first column are equal then for such rows we sort them by second column. If in second column values are equal then we look on the third column and so on. It is like lexicographic sort for strings – Nourless Jul 12 '21 at 09:50

1 Answers1

0

This should work

import numpy as np

a = np.array([[1, 0, 4, 2, 3],[0, 1, 5, 7, 4],[0, 0, 6, 1, 0]])

np.sort(a.view('i8,i8,i8,i8,i8'), order=['f0'], axis=0).view(np.int)

I get

array([[0, 0, 6, 1, 0],
       [0, 1, 5, 7, 4],
       [1, 0, 4, 2, 3]])

f0 is the column which you want to sort by.

anarchy
  • 3,709
  • 2
  • 16
  • 48