numpy:替换数组中的随机元素

编程入门 行业动态 更新时间:2024-10-25 18:23:46
本文介绍了numpy:替换数组中的随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经在Google上搜索了一下,但没有发现任何好处 答案.

I already googled a bit and didn't find any good answers.

问题是,我有一个二维的numpy数组,我想 在随机位置替换其某些值.

The thing is, I have a 2d numpy array and I'd like to replace some of its values at random positions.

我使用numpy.random.choice创建了一些答案 阵列的遮罩.不幸的是,这并没有创造 原始数组上的视图,因此我无法替换其值.

I found some answers using numpy.random.choice to create a mask for the array. Unfortunately this does not create a view on the original array so I can not replace its values.

所以这是我想做的事的一个例子.

So here is an example of what I'd like to do.

想象一下我有一个带有浮点值的二维数组.

Imagine I have 2d array with float values.

[[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]]

然后我想替换任意数量的 元素.如果我可以调整参数会很好 多少元素将被替换. 可能的结果如下所示:

And then I'd like to replace an arbitrary amount of elements. It would be nice if I could tune with a parameter how many elements are going to be replaced. A possible result could look like this:

[[ 3.234, 2., 3.], [ 4., 5., 6.], [ 7., 8., 2.234]]

我想不出什么好办法来实现这一目标. 感谢您的帮助.

I couldn't think of nice way to accomplish this. Help is appreciated.

编辑

感谢所有快速答复.

推荐答案

只需使用相同形状的任意一个遮罩您的输入数组即可.

Just mask your input array with a random one of the same shape.

import numpy as np # input array x = np.array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]]) # random boolean mask for which values will be changed mask = np.random.randint(0,2,size=x.shape).astype(np.bool) # random matrix the same shape of your data r = np.random.rand(*x.shape)*np.max(x) # use your mask to replace values in your input array x[mask] = r[mask]

产生这样的东西:

[[ 1. 2. 3. ] [ 4. 5. 8.54749399] [ 7.57749917 8. 4.22590641]]

更多推荐

numpy:替换数组中的随机元素

本文发布于:2023-11-10 15:44:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575783.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   元素   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!