53

I have two related numpy arrays, X and y. I need to select n random rows from X and store this in an array, the corresponding y value and the appends to it the index of the points randomly selected.

I have another array index which stores a list of index which I dont want to sample.

How can I do this?

Sample data:

index = [2,3]
X = np.array([[0.3,0.7],[0.5,0.5] ,[0.2,0.8], [0.1,0.9]])
y = np.array([[0], [1], [0], [1]])

If these X's were randomly selected (where n=2):

randomylSelected = np.array([[0.3,0.7],[0.5,0.5]])

the desired output would be:

index = [0,1,2,3]
randomlySelectedY = [0,1]

How can I do this?

5
  • So, is randomylSelected given or to be created? Commented Apr 19, 2017 at 21:58
  • To be created by randomly selecting n rows from X. @Divakar Commented Apr 19, 2017 at 22:00
  • Could you please clarify how your index changes from [2,3] to [0,1] when it's not sampled? What's the purpose of the index and how does it relate to the other arrays? Commented Apr 19, 2017 at 22:26
  • @MSeifert index contains a list of items already sampled which should not be sampled again. Commented Apr 19, 2017 at 23:21
  • 1
    @scutnex In that case: Thanks for the clarification but you should rather ask a new question instead of changing the question (after it received answers) in such fundamental ways. Could you please rollback your question to the original version and ask a new question? Commented Apr 20, 2017 at 8:35

2 Answers 2

87

You can create random indices with np.random.choice:

n = 2  # for 2 random indices
index = np.random.choice(X.shape[0], n, replace=False)  

Then you just need to index your arrays with the result:

x_random = X[index]
y_random = Y[index]
Sign up to request clarification or add additional context in comments.

Comments

12

just to wrap @MSeifert 's answer in a function:

def random_sample(arr: numpy.array, size: int = 1) -> numpy.array:
    return arr[np.random.choice(len(arr), size=size, replace=False)]

useage:

randomly_selected_y = random_sample(Y)

1 Comment

Seriously why is there no function for this, that is such a common use case. So annoying.

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.