Creating a string
of each row
and then applying np.sort()
So if we have an array
to test on:
a = np.array([[1,0,0,0],[0,0,0,0],[1,1,1,1],[0,0,1,1]])
We can create strings
of each row
by using np.apply_along_axis
:
a = np.apply_along_axis(lambda r: ''.join([str(c) for c in r]), 0, a)
which would make a
now:
array(['1010', '0010', '0011', '0011'], dtype='<U4')
and so now we can sort
the strings
with np.sort()
:
a = np.sort(a)
making a
:
array(['0010', '0011', '0011', '1010'], dtype='<U4')
we can then convert back to the original format with:
a = np.array([[int(i) for i in r] for r in a])
which makes a
:
array([[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 1, 1],
[1, 0, 1, 0]])
And if you wanted to cram this all into one line:
a = np.array([[int(i) for i in r] for r in np.sort(np.apply_along_axis(lambda r: ''.join([str(c) for c in r]), 0, a))])