0

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.

2
  • Please share your effort on your for-loop so that we can help you fix or correct it. Commented Feb 27, 2017 at 21:55
  • I love too, but it is not very clear otherwise I will share it, thanks Commented Feb 27, 2017 at 22:19

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much that was very helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.