Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

np.full(size, 0) vs. np.zeros(size) vs. np.empty()

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 
like image 391
Dataman Avatar asked Oct 06 '14 09:10

Dataman


People also ask

What is the difference between NP empty and NP zeros?

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.

What does NP empty () do?

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.

What is the use of zeros () function in Numpy?

Python numpy. zeros() function returns a new array of given shape and type, where the element's value as 0.

Why does Numpy empty have values?

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.


1 Answers

I'd use np.zeros, because of its name. I would never use the third idiom because

  1. it takes two statements instead of a single expression and

  2. 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 
like image 70
Fred Foo Avatar answered Sep 21 '22 23:09

Fred Foo