What's difference between np.zeros(img) and np.copy(img)*0?

Question:

What is the difference between these three:

np.zeros(img), np.zeros_like(img), and np.copy(img)*0?

When should I use each of them?

Asked By: AnkS

||

Answers:

zeros is the basic operation, creating an array with a given shape and dtype:

In [313]: arr = np.zeros((3,4),int)
In [314]: arr
Out[314]: 
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])

zeros_like is an alternative input to zeros, where you provide an array, and it copies its shape and dtype (but not values):

In [315]: bar = np.zeros_like(arr)
In [316]: bar
Out[316]: 
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])

copy*0 also works, but generally I wouldn’t recommend it. I did use N2 *=0 recently in while testing some code to reset an array.

In [317]: car = arr.copy()*0
In [318]: car
Out[318]: 
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])
Answered By: hpaulj

screenshot of the python codes

Despite they can reach a similar effect of creating a zero NumPy array of the shape you intended. Their performances are significantly different.

As shown in the screenshot below, np.zeros_like(x) is slightly slower than np.zeros(x.shape) while np.copy(x)*0 is the slowest of all.

For example, if you increase the array size, you can really see the difference here:

enter image description here

Answered By: CyTex
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.