我使用 np.random.randn
data = np.random.randn(1, 10)
我得到的输出
[[-0.92408284 -2.61254901 0.95036968 0.81644508 -1.523876 -0.42804606
-0.74240684 -0.7033438 -2.13962066 -0.62947496]]
现在,如果我想改变极大或极小的 2/3 值(即 0.95036968 into 95.03
和 -2.13962066 into -213.96
),那么我必须做什么?
在这里,我需要控制要更改的数字 (2/3/4) 和更改范围(例如,+100 到 -300),它们可以随机更改任何数字。
预期输出:
[[-0.92408284 -2.61254901 95.03 0.81644508 -1.523876 -0.42804606
-0.74240684 -0.7033438 -213.96 -0.62947496]]
答案 0 :(得分:0)
data = np.random.randn(1, 10)
# indexes to change
# (can be random too: `np.random.choice(np.arange(data.size), size=3)`
inds_to_change = [2, 3, 5]
# range of values to consider for the difference
lower, upper = -300, +100
# sampling some differences
diffs = np.random.choice(np.arange(lower, upper), size=len(inds_to_change))
# changing array values
data[:, inds_to_change] += diffs
对于给定的变化的下限和上限,我们使用 np.random.choice
来采样一些差异来应用。然后我们对数组进行索引并将它们添加到预定义索引的位置(或者也可以是随机的)。
样品运行:
# to see a cleaner output
>>> np.set_printoptions(suppress=True)
>>> data = np.random.randn(1, 10)
>>> data
array([[-0.29, 0.11, 1.25, -1.36, 0.1 , -0.05, -0.36, -1.09, -0.35,
2.59]])
>>> inds_to_change = [2, 3, 5]
>>> lower, upper = -300, +100
>>> diffs = np.random.choice(np.arange(lower, upper), size=len(inds_to_change))
>>> diffs
array([ 94, -294, -19])
>>> data[:, inds_to_change] += diffs
>>> data
array([[ -0.29, 0.11, 95.25, -295.36, 0.1 , -19.05, -0.36,
-1.09, -0.35, 2.59]])