python 之 np.random.choice()

用法:np.random.choice(a, size=None, replace=True, p=None)

返回:从一维array a 或 int 数字a 中,以概率p随机选取大小为size的数据,replace表示是否重用元素,即抽取出来的数据是否放回原数组中,默认为true(抽取出来的数据有重复)

#在(0,5)区间内生成含5个数据的一维数组
>>a = np.random.randint(0, 5, (5,))
>>print('a = ', a)
    a =  [2 1 2 1 3]
#在a数组中抽取6个数,replace为true
>>b = np.random.choice(a, 6)
>>print('b = ', b)
    b =  [1 1 2 2 1]
#replace为False时,size需小于等于len(a)
>>c = np.random.choice(a, 5, replace=False, p=None)
>>print('c = ', c)
    c =  [3 2 1 1 2]
#p是数组a中所有数出现的概率,总和为1
>>d = np.random.choice(a, 5, replace=False, p=[0.2, 0.3, 0.1, 0.3, 0.1])
>>print('d = ', d)
    d =  [1 3 2 1 2]

猜你喜欢

转载自blog.csdn.net/weixin_42338058/article/details/84023785