azeez -4 years ago 188

Python Question

I have two arrays one Int, and one is bit

`s = [ [1] x = [ [1 0 0 0 0]`

[4] [1 1 1 1 0]

[9] [0 1 1 1 0]

[0] [0 0 1 0 0]

[3] ] [0 1 1 0 0]]

I want to find the smallest two elements in s (random given) then (select and print) two rows from x (random given) based on s array,

for example, the smallest elements in s[i] are s[3]=0, s[0]=1, so i want to select x[3][0 0 1 0 0], and x[0][1 0 0 0 0]

`import numpy as np`

np.set_printoptions(threshold=np.nan)

s= np.random.randint(5, size=(5))

x= np.random.randint (2, size=(5, 5))

print (s)

print (x)

I tried my best using the "for loop" but no luck, any advice will be appreciated.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You can use numpy.argpartition to find out the index of the two smallest elements from `s`

and use it as row index to subset `x`

:

```
s
# array([3, 0, 0, 1, 2])
x
# array([[1, 0, 0, 0, 1],
# [1, 0, 1, 1, 1],
# [0, 0, 1, 0, 0],
# [1, 0, 0, 1, 1],
# [0, 0, 1, 0, 1]])
x[s.argpartition(2)[:2], :]
# array([[1, 0, 1, 1, 1],
# [0, 0, 1, 0, 0]])
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**

Latest added