# [Numpy-discussion] Fwd: Numpy for data manipulation

Jaime Fernández del Río jaime.frio at gmail.com
Thu Oct 1 20:05:18 EDT 2015

```On Thu, Oct 1, 2015 at 11:46 AM, Alex Rogozhnikov <
alex.rogozhnikov at yandex.ru> wrote:

> Hi, I have written some numpy tips and tricks I am using, which may be
> interesting to you.
> This is quite long reading, so I've splitted it into two parts:
>
> http://arogozhnikov.github.io/2015/09/29/NumpyTipsAndTricks1.html

The recommendation of inverting a permutation by argsort'ing it, while it
works, is suboptimal, as it takes O(n log(n)) time, and you can do it in
linear time:

In [14]: import numpy as np

In [15]: arr = np.random.rand(10)

In [16]: perm = arr.argsort()

In [17]: perm
Out[17]: array([5, 0, 9, 4, 2, 8, 6, 7, 1, 3])

In [18]: inv_perm = np.empty_like(perm)

In [19]: inv_perm[perm] = np.arange(len(perm))

In [20]: np.all(inv_perm == perm.argsort())
Out[20]: True

It does require two lines of code, so for small stuff it is probably good
enough to argsort, but it gave e.g. np.unique a nice boost on larger arrays
when we applied it there.

Jaime

>
> http://arogozhnikov.github.io/2015/09/30/NumpyTipsAndTricks2.html
>
> Comments are welcome, specially if you know any other ways to make this
> code faster (or better).
>
> Regards,
> Alex.
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> https://mail.scipy.org/mailman/listinfo/numpy-discussion
>

--
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus planes
de dominación mundial.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20151001/d69de73e/attachment.html>
```

More information about the NumPy-Discussion mailing list