在numpy.random.normal阵列替换值 [英] Replace value in array with numpy.random.normal

查看:623
本文介绍了在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)
我该怎么做?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆