Reputation: 1051
I have an array A, I want to create arrays B and C.
Basically, I want to randomly find 100 elements in A, put them in B and the rest in C.
If I use numpy.random.choice I can easily create B by just extracting all the elements in A that match the indices in the random list, but I would have to go through A again in order to find all the values that are not in B and put them in C. This works, but maybe there is a built-in function that can do this for me.
Is there a cheaper way?
Upvotes: 1
Views: 99
Reputation: 624
You can use this, numpy inbuilt function
import numpy as np
import random
a = np.array([1,2,3,4,5,6,7,8,9,10]);
b = np.array(random.sample(a.values,3));
c = np.setdiff1d(a,b)
Upvotes: 0
Reputation: 29337
You could select elements from the array using indices and create a boolean mask like this:
indices = np.random.choice(len(a),3) # pick indices at random from array a
mask = np.ones(a.shape,dtype=bool) # create boolean mask
mask[indices] = False
a[indices] # random elements from array
a[mask] # rest of array
Upvotes: 3