Best way to initialize and fill an numpy array?
You could also try:
In [79]: np.full(3, np.nan)Out[79]: array([ nan, nan, nan])
The pertinent doc:
Definition: np.full(shape, fill_value, dtype=None, order='C')Docstring:Return a new array of given shape and type, filled with `fill_value`.
Although I think this might be only available in numpy 1.8+
np.fill
modifies the array in-place, and returns None
. Therefor, if you're assigning the result to a name, it gets a value of None
.
An alternative is to use an expression which returns nan
, e.g.:
a = np.empty(3) * np.nan
I find this easy to remember:
numpy.array([numpy.nan]*3)
Out of curiosity, I timed it, and both @JoshAdel's answer and @shx2's answer are far faster than mine with large arrays.
In [34]: %timeit -n10000 numpy.array([numpy.nan]*10000)10000 loops, best of 3: 273 µs per loopIn [35]: %timeit -n10000 numpy.empty(10000)* numpy.nan10000 loops, best of 3: 6.5 µs per loopIn [36]: %timeit -n10000 numpy.full(10000, numpy.nan)10000 loops, best of 3: 5.42 µs per loop