Malintha - 10 months ago 51

Python Question

I have an array

`[2, 4, 2, 1, 3, 2, 2]`

`import bottleneck`

import numpy as np

a = np.array([2, 4, 2, 1, 3, 2, 2])

b = np.array(bottleneck.argpartsort(-a, 3)[:3])

print(b)

which gives

`[4 1 5]`

Answer Source

You can use `np.argsort`

```
import numpy as np
a = np.array([2, 4, 2, 1, 3, 2, 2])
b = np.argsort(a)[-3:]
b = b[::-1]
```

Note: The last two lines can further be simplified to (although with not much computational advantage)

```
b = np.argsort(a)[-3:][::-1]
# or, as juanpa suggested
b = np.argsort(a)[-1:-4:-1]
```

All give the following value of `b`

```
array([1, 4, 6])
```