Python 从numpy数组中随机选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43506766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Randomly select from numpy array
提问by scutnex
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.
我有两个相关的 numpy 数组,X
和y
. 我需要从中选择n
随机行X
并将其存储在一个数组中,相应的y
值并将随机选择的点的索引附加到它。
I have another array index
which stores a list of index which I dont want to sample.
我有另一个数组index
,它存储我不想采样的索引列表。
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
):
如果这些X
是随机选择的(其中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?
我怎样才能做到这一点?
回答by MSeifert
You can create random indices with np.random.choice
:
您可以使用以下方法创建随机索引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]
回答by Alon Gouldman
just to wrap @MSeifert 's answer in a function:
只是为了将 @MSeifert 的答案包装在一个函数中:
def random_sample(arr: numpy.array, size: int = 1) -> numpy.array:
return arr[np.random.choice(len(arr), size=size, replace=False)]
useage:
用途:
randomlySelectedY = random_sample(Y)