I want to initialize and fill a numpy
array. What is the best way?
This works as I expect:
>>> import numpy as np
>>>
Just for future reference, the multiplication by np.nan
only works because of the mathematical properties of np.nan
.
For a generic value N
, one would need to use np.ones() * N
mimicking the accepted answer, however, speed-wise, this is not a terribly good choice.
Best choice would be np.full()
as already pointed out, and, if that is not available for you, np.zeros() + N
seems to be a better choice than np.ones() * N
, while np.empty() + N
or np.empty() * N
are simply not suitable. Note that np.zeros() + N
will also work when N
is np.nan
.
%timeit x = np.full((1000, 1000, 10), 432.4)
8.19 ms ± 97.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit x = np.zeros((1000, 1000, 10)) + 432.4
9.86 ms ± 55.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit x = np.ones((1000, 1000, 10)) * 432.4
17.3 ms ± 104 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit x = np.array([432.4] * (1000 * 1000 * 10)).reshape((1000, 1000, 10))
316 ms ± 37.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)