Sort Numpy Array With Custom Predicate
I'd like to sort my numpy array of shape [n,4], along first dimension (size:n) using a custom predicate operating on the 2nd dimension vector (size:4). The C++ version of what I'd
Solution 1:
In numpy you would apply the (vectorized) order defining function to the array, then use np.argsort
to sort by the result.
This is less space efficient than the C++ version, but that is how you usually achieve performance with numpy.
import numpy as np
defmyfn(x):
return np.sin(x[:, 1]) # example: sort by the sine of the second column
a = np.random.randn(10, 4)
predicate = myfn(a) # not sure if predicate is the best name for this variable
order = np.argsort(predicate)
a_sorted = a[order]
Post a Comment for "Sort Numpy Array With Custom Predicate"