Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

python - Randomly select from numpy array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...