I have a numpy matrix like so:
array([[2, 1, 23, 32],
[34, 3, 3, 0],
[3, 33, 0, 0],
[32, 0, 0, 0]], dtype=int32)
Now
You can also perform sorting on the masked array with the help of numpy.ma.sort() that sorts the array in-place along the last axis, axis=-1
as shown:
np.ma.array(a, mask=a!=0).sort()
Now a
becomes:
array([[ 2, 1, 23, 32],
[ 0, 34, 3, 3],
[ 0, 0, 3, 33],
[ 0, 0, 0, 32]])
The only downside is that it is not as fast as some of the approaches mentioned above but nevertheless a short one-liner to have.