python:numpy从数组中随机抽取元素

这篇博客介绍了如何使用numpy库在Python中生成随机数。通过`np.random.choice`函数,可以以指定概率从给定列表中抽取样本,例如生成0和1的序列,或者模拟英语阅读答案的选择分布。此功能在数据模拟和实验设计中有广泛应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 以0.5的概率选取0或1生成10个数据
np.random.choice([0,1],size=10,p=[.5,.5])
# [0 1 0 0 1 0 0 0 0 1]

# 生成英语“阅读答案”
np.random.choice(['A', 'B', 'C', 'D'], 20, p=[0.25, 0.25, 0.25, 0.25])
# ['D' 'D' 'A' 'B' 'A' 'C' 'C' 'D' 'D' 'B' 'A' 'D' 'A' 'C' 'D' 'D' 'D' 'B'
 'D' 'C']
numpy.random.choice(a, size=None, replace=True, p=None)
可以从一个int数字或1维array里随机选取内容,并将选取结果放入n维array中返回。

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,可选参数
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,可选参数
Whether the sample is with or without replacement

p : 1-D array-like, 可选参数
The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值