将numpy矩阵初始化为零或一个以外的值(Initializing numpy matrix to something other than zero or one)

编程入门 行业动态 更新时间:2024-10-26 08:29:28
将numpy矩阵初始化为零或一个以外的值(Initializing numpy matrix to something other than zero or one)

我有以下代码:

r = numpy.zeros(shape = (width, height, 9))

它创建一个宽度x高x 9矩阵,填充零。 相反,我想知道是否有一个函数或方法来初始化它们而不是NaN。

有没有? 无需手动执行循环等等?

谢谢

I have the following code:

r = numpy.zeros(shape = (width, height, 9))

It creates a width x height x 9 matrix filled with zeros. Instead, I'd like to know if there's a function or way to initialize them instead to NaN.

Is there any? Without having to resort to manually doing loops and such?

Thanks

最满意答案

您很少需要循环用于numpy中的向量操作。 您可以创建一个未初始化的数组并一次分配给所有条目:

>>> a = numpy.empty((3,3,)) >>> a[:] = numpy.NAN >>> a array([[ NaN, NaN, NaN], [ NaN, NaN, NaN], [ NaN, NaN, NaN]])

我已经将这些替代品定a[:] = numpy.nan和a.fill(numpy.nan)发布的a.fill a.fill(numpy.nan) :

$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a.fill(np.nan)" 10000 loops, best of 3: 54.3 usec per loop $ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a[:] = np.nan" 10000 loops, best of 3: 88.8 usec per loop

时间表示偏好ndarray.fill(..)作为更快的选择。 OTOH,我喜欢numpy的方便实现,您可以在此时为整个片段分配值,代码的意图非常明确。

You rarely need loops for vector operations in numpy. You can create an uninitialized array and assign to all entries at once:

>>> a = numpy.empty((3,3,)) >>> a[:] = numpy.nan >>> a array([[ NaN, NaN, NaN], [ NaN, NaN, NaN], [ NaN, NaN, NaN]])

I have timed the alternatives a[:] = numpy.nan here and a.fill(numpy.nan) as posted by Blaenk:

$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a.fill(np.nan)" 10000 loops, best of 3: 54.3 usec per loop $ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a[:] = np.nan" 10000 loops, best of 3: 88.8 usec per loop

The timings show a preference for ndarray.fill(..) as the faster alternative. OTOH, I like numpy's convenience implementation where you can assign values to whole slices at the time, the code's intention is very clear.

更多推荐

本文发布于:2023-07-29 20:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1319527.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   初始化   为零   numpy   Initializing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!