If you were to choose one of the following three ways of initializing an array with zeros which one would you choose and why?
my_arr_1 = np.full(size, 0)
or
my_arr_2 = np.zeros(size)
or
my_arr_3 = np.empty(size) my_arr_3[:] = 0
empty , unlike zeros , does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.
The empty() function is used to create a new array of given shape and type, without initializing entries. Shape of the empty array, e.g., (2, 3) or 2. Desired output data-type for the array, e.g, numpy. int8.
Python numpy. zeros() function returns a new array of given shape and type, where the element's value as 0.
NumPy empty produces arrays with arbitrary values The np. empty function actually does fill the array with values. It's just that the values are completely arbitrary. The values are not quite “random” like the numbers you get from the np.
I'd use np.zeros
, because of its name. I would never use the third idiom because
it takes two statements instead of a single expression and
it's harder for the NumPy folks to optimize. In fact, in NumPy 1.10, np.zeros
is still the fastest option, despite all the optimizations to indexing:
>>> %timeit np.zeros(1e6) 1000 loops, best of 3: 804 µs per loop >>> %timeit np.full(1e6, 0) 1000 loops, best of 3: 816 µs per loop >>> %timeit a = np.empty(1e6); a[:] = 0 1000 loops, best of 3: 919 µs per loop
Bigger array for comparison with @John Zwinck's results:
>>> %timeit np.zeros(1e8) 100000 loops, best of 3: 9.66 µs per loop >>> %timeit np.full(1e8, 0) 1 loops, best of 3: 614 ms per loop >>> %timeit a = np.empty(1e8); a[:] = 0 1 loops, best of 3: 229 ms per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With