I'm trying to sort a matrix if I have
[[5 7 1 2]
[4 8 1 4]
[4 0 1 9]
[2 7 5 0]]
I want this result
[[9 8 7 7]
[5 5 4 4]
[4 2 2 1]
[1 1 0 0]]
this is my code, I'm using random numbers
import numpy as np
MatriX = np.random.randint(10, size=(4,4))
print(MatriX)
for i in range(10):
for j in range(10):
a=np.sort(-MatriX,axis=1)*-1
b=np.sort(-a,axis=0)*-1
c=np.transpose(b)
d=np.sort(-c,axis=1)*-1
e=np.sort(-d,axis=0)*-1
print(e)
but this code, don't work at all
It's as simple as this:
import numpy as np
data = np.random.randint(10, size=(4,4))
print(data)
result = np.sort(data.flatten())[::-1].reshape(data.shape)
print(result)
Output:
[[4 7 7 6]
[1 9 5 0]
[5 8 1 2]
[2 5 7 3]]
[[9 8 7 7]
[7 6 5 5]
[5 4 3 2]
[2 1 1 0]]
An explanation of the parts of np.sort(data.flatten())[::-1].reshape(data.shape)
:
data.flatten()
flattens the array into a one-dimensional shape and returns the resultnp.sort()
sorts the one-dimensional result and returns the sorted data[::-1]
reverses the order of the sorted data.reshape(data.shape)
applies the shape of the original data to that reversed sorted dataNote that something like this would be easier to read:
result = data.flattened().sorted().reversed().reshaped(data.shape)
But numpy
doesn't implement all the needed methods that allow for this more readable chaining and many methods make changes in-place. So you get the slightly harder to read solution above instead. (you could define a class that has these, but your code wouldn't make sense to others familiar with numpy
, so it is probably best left the way it is)
However, if your data is large, performing some operations in-place may make more sense. The solution given here is intended to be simple, you may want to look at some optimisation for very large data.