tirsdag den 8. september 2015

Inverting a sort the easy way

Suppose you are working with an array:

> X = [10, 40, 20]

And you'd like to do some operations on a sorted version of X, then translate those operations back into X's original order.
The simple way to do this is using Numpy's argsort:

> s = np.argsort(X)
> invs = np.argsort(s)

For instance, to get the cumulative sum of X's elements, when summing up from lowest to highest, do:

> scX = X[s].cumsum()
> cX = scX[invs]
> print cX

[10, 70, 30]

Ingen kommentarer:

Send en kommentar