Create numpy matrix filled with NaNs

后端 未结 8 1297
灰色年华
灰色年华 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:26

    You can always use multiplication if you don't immediately recall the .empty or .full methods:

    >>> np.nan * np.ones(shape=(3,2))
    array([[ nan,  nan],
           [ nan,  nan],
           [ nan,  nan]])
    

    Of course it works with any other numerical value as well:

    >>> 42 * np.ones(shape=(3,2))
    array([[ 42,  42],
           [ 42,  42],
           [ 42, 42]])
    

    But the @u0b34a0f6ae's accepted answer is 3x faster (CPU cycles, not brain cycles to remember numpy syntax ;):

    $ python -mtimeit "import numpy as np; X = np.empty((100,100));" "X[:] = np.nan;"
    100000 loops, best of 3: 8.9 usec per loop
    (predict)laneh@predict:~/src/predict/predict/webapp$ master
    $ python -mtimeit "import numpy as np; X = np.ones((100,100));" "X *= np.nan;"
    10000 loops, best of 3: 24.9 usec per loop
    

提交回复
热议问题