如何将numpy数组中的元素随机设置为0 [英] How to randomly set elements in numpy array to 0

查看:348
本文介绍了如何将numpy数组中的元素随机设置为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我创建我的数组

myarray = np.random.random_integers(0,10, size=20)

然后,我想将数组中20%的元素设置为0(或其他一些数字).我应该怎么做?戴口罩?

Then, I want to set 20% of the elements in the array to 0 (or some other number). How should I do this? Apply a mask?

推荐答案

您可以使用np.random.choice计算索引,将所选索引的数量限制为百分比:

You can calculate the indices with np.random.choice, limiting the number of chosen indices to the percentage:

indices = np.random.choice(np.arange(myarray.size), replace=False,
                           size=int(myarray.size * 0.2))
myarray[indices] = 0

这篇关于如何将numpy数组中的元素随机设置为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆