在numpy.random.normal阵列替换值 [英] Replace value in array with numpy.random.normal
问题描述
我有以下数组:
myArray1 = np.array([[255, 255, 255, 1, 1, 255, 255, 255],
[255, 1, 1, 1, 1, 1, 255, 255]])
我要创建 myArray2
新阵列基于 myArray1
。其中, myArray1
的值为1,我要取代 numpy.random.normal(LOC = 40,比例= 10)价值code>。
我该怎么做?
I want to create a new array myArray2
based on myArray1
. Where myArray1
has a value of 1, I want to replace the value by numpy.random.normal(loc=40, scale=10)
.
How can I do that?
推荐答案
如果您的数组被称为 A
,你可以做
If your array is called a
, you can do
b = a == 1
a[b] = numpy.random.normal(loc=40, scale=10, size=b.sum())
这避免了Python的循环和采取的numpy的性能优势。
This avoids Python loops and takes advantage of Numpy's performance.
第一行创建具有相同形状的布尔数组为 A
是真
在对应的所有条目为那些在 A
。第二行使用高级索引这个布尔数组以指定新的价值只有其中, b
是地方真
。
The first line creates a Boolean array with the same shape as a
that is True
in all entries that correspond to ones in a
. The second line uses advanced indexing with this Boolean array to assign new values only to the places where b
is True
.
这篇关于在numpy.random.normal阵列替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!