【numpy】np.random.choice

np.random.choice(a, size=None, replace=True, p=None)
#a为一维数组或者int,size默认None,此时返回一个值,也可以为int或者tuple,replace=True为有放回的选择,可能出现重复,p为概率列表,之和应该为1.
Parameters:
   a : 1-D array-like or int
       If an ndarray, a random sample is generated from its elements.
       If an int, the random sample is generated as if a were np.arange(a)
   size : int or tuple of ints, optional
       Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
       ``m * n * k`` samples are drawn.  Default is None, in which case a
       single value is returned.
   replace : boolean, optional
       Whether the sample is with or without replacement
   p : 1-D array-like, optional
       The probabilities associated with each entry in a.
       If not given the sample assumes a uniform distribution over all
       entries in a.

   Returns
   -------
   samples : single item or ndarray
       The generated random samples
import numpy as np

if __name__=="__main__":
    a = np.random.choice(5, 3, replace=True, p=[0.1,0.1,0.2,0.4,0.2])#表示从0~4中随机选择3个,且有放回,可重复
    print(a)

    b = np.random.choice(5, 3, replace=False, p=[0.1, 0.1, 0.2, 0.4, 0.2])
    print(b)

#output:
[4 4 2]
[3 4 2]

猜你喜欢

转载自blog.csdn.net/YJYS_ZHX/article/details/113520500