问题描述
我已经在Google上搜索了一下,但没有发现任何好处答案.
I already googled a bit and didn't find any goodanswers.
问题是,我有一个二维的numpy数组,我想在随机位置替换其某些值.
The thing is, I have a 2d numpy array and I'd like toreplace some of its values at random positions.
我使用numpy.random.choice创建了一些答案阵列的遮罩.不幸的是,这并没有创造原始数组上的视图,因此我无法替换其值.
I found some answers using numpy.random.choice to createa mask for the array. Unfortunately this does not createa 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 ofelements. It would be nice if I could tune with a parameterhow 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:替换数组中的随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!