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

Nim*_*avi 8 python random numpy

我已经google了一下,没有找到任何好的答案.

问题是,我有一个2d numpy数组,我想在随机位置替换它的一些值.

我找到了一些使用numpy.random.choice为数组创建掩码的答案.不幸的是,这不会在原始数组上创建视图,因此我无法替换其值.

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

想象一下,我有2d数组的浮点值.

[[ 1., 2., 3.],
 [ 4., 5., 6.],
 [ 7., 8., 9.]]
Run Code Online (Sandbox Code Playgroud)

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

[[ 3.234, 2., 3.],
 [ 4., 5., 6.],
 [ 7., 8., 2.234]]
Run Code Online (Sandbox Code Playgroud)

我无法想到实现这一目标的好方法.感谢帮助.

编辑

感谢所有快速回复.

der*_*icw 8

只需使用相同形状的随机数字屏蔽输入数组.

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]
Run Code Online (Sandbox Code Playgroud)

产生这样的东西:

[[ 1.          2.          3.        ]
 [ 4.          5.          8.54749399]
 [ 7.57749917  8.          4.22590641]]
Run Code Online (Sandbox Code Playgroud)

  • 要改变要替换的*预期*元素数量,请使用 `mask = np.random.choice([0, 1], size=x.shape, p=((1 - Replace_rate), Replace_rate)).astype(np .bool)` 而不是上面的 `randint`,这相当于使用上面的 `np.random.choice` 和 `replace_rate = 0.5`。 (4认同)

Dil*_*rix 5

当数组是一维时,很容易随机选择索引,因此我建议将数组重新整形为一维,更改随机元素,然后重新整形回原始形状。

例如:

import numpy as np

def replaceRandom(arr, num):
    temp = np.asarray(arr)   # Cast to numpy array
    shape = temp.shape       # Store original shape
    temp = temp.flatten()    # Flatten to 1D
    inds = np.random.choice(temp.size, size=num)   # Get random indices
    temp[inds] = np.random.normal(size=num)        # Fill with something
    temp = temp.reshape(shape)                     # Restore original shape
    return temp
Run Code Online (Sandbox Code Playgroud)

所以这会做一些类似的事情:

>>> test = np.arange(24, dtype=np.float).reshape(2,3,4)
>>> print replaceRandom(test, 10)
[[[  0.          -0.95708819   2.           3.        ]
  [ -0.35466096   0.18493436   1.06883205   7.        ]
  [  8.           9.          10.          11.        ]]
 [[ -1.88613449  13.          14.          15.        ]
  [  0.57115795  -1.25526377  18.          -1.96359786]
  [ 20.          21.           2.29878207  23.        ]]]
Run Code Online (Sandbox Code Playgroud)

在这里,我替换了从正态分布中选择的元素 --- 但显然你可以用np.random.normal你想要的任何东西替换调用。