numpy.random.choice¶
-
numpy.random.
choice
(a, size=None, replace=True, p=None)¶ Generates a random sample from a given 1-D array
New in version 1.7.0.
Parameters: a : 1-D array-like or int
If an ndarray, a random sample is generated from its elements. 如果是int,则生成随机样本,如同a是np.arange(n)
size : int or tuple of ints, optional
输出的形状。如果给定形状是例如
(m, n, k)
,则抽取m * n * k
个样本。Default is None, in which case a single value is returned.replace:boolean,可选
采样是否有重复
p:1-D array-like,可选
The probabilities associated with each entry in a. 如果没有给出样本,则假设在a中的所有条目均匀分布。
Returns: samples:1-D字符串,形状(size,)
The generated random samples
引发: ValueError
If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size
另见
Examples
从np.arange(5)生成大小为3的均匀随机样本:
>>> np.random.choice(5, 3) array([0, 3, 4]) >>> #This is equivalent to np.random.randint(0,5,3)
从np.arange(5)生成大小为3的非均匀随机样本:
>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0])
从np.arange(5)生成大小为3的均匀随机样本,没有重复:
>>> np.random.choice(5, 3, replace=False) array([3,1,0]) >>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
从np.arange(5)生成大小为3的非均匀随机样本,没有重复:
>>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) array([2, 3, 0])
上述任何一个例子都可以使用一个类似数组的对象重新运行,而不是只是用整数。For instance:
>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], dtype='|S11')