Create numpy matrix filled with NaNs

后端 未结 8 1269
灰色年华
灰色年华 2020-12-04 07:40

I have the following code:

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

It creates a width x height x 9 matrix filled with zero

8条回答
  •  抹茶落季
    2020-12-04 08:27

    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.

    Note that ndarray.fill performs its operation in-place, so numpy.empty((3,3,)).fill(numpy.nan) will instead return None.

提交回复
热议问题