我有一个数组
my_array = np.array([1,0,1,0,0,1,1,0,1,0])
在这个数组中,50%的项目是1。我想有效地随机地将一些1切换到0,这样比例就达到20%。你知道吗
new_array = switch_function(my_array)
print new_array
array([0,0,0,0,0,1,0,0,1,0]) #random switching retaining order
这看起来应该很简单,我所想的一切似乎都设计过度了。谢谢你的帮助!你知道吗
Tags:
IIUC,这样应该行得通:
首先我们计算出需要翻转多少个数字(尽量接近正确的值),然后随机选择
n
个非零索引,最后将它们设置为零。你知道吗注意,正如JFS在注释中所指出的,您应该验证
n > 0
,以确保您不会意外地做出您不想做的更改。你知道吗完成这类任务有很多方法。这里有一个简单的方法。你知道吗
如果您不需要将现有的零保持为零,并且只希望整个数组的平均值为20%1,那么您是否可以使用“for”循环遍历数组,并为每个元素调用randint(1,5)。如果randint返回1,则将数组项设置为1,否则将其设置为0。你知道吗
但是,如果您希望保留所有原始的零,这意味着您希望将1的数量减少到现在数字的40%,因此遍历数组,如果数字是1,则调用randint(1,5),如果它返回1或2,则保留原始的1,否则将其更改为零。你知道吗
相关问题 更多 >
编程相关推荐