Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of numpy.empty() over numpy.ndarray()?

Tags:

numpy

It seems that anything that numpy.empty() can do can be done just as easily using numpy.ndarray(), e.g.:

>>> np.empty(shape=(2, 2), dtype=np.dtype('double'))
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> np.ndarray(shape=(2, 2), dtype=np.dtype('double'))
array([[ 0.,  0.],
       [ 0.,  0.]])
>>>

Why do we need numpy.empty()? Can it do something that numpy.ndarray() cannot do just as simply? Is it just serving an annotational purpose to emphasize to the code reader that you are creating an uninitialized array?

like image 535
Joshua Chia Avatar asked Sep 13 '25 20:09

Joshua Chia


1 Answers

Always use np.empty. np.ndarray is the low-level way to construct an array. It is used by np.empty or np.array. np.ndarray exposes some details you should not (accidentally) use yourself.

From the docstring:

Docstring:

ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)

Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(...)) for instantiating an array.

For more information, refer to the numpy module and examine the the methods and attributes of an array.

Get the docstring with:

>>> help(np.ndarray)

or in IPython:

In: [1] np.ndarray?

EDIT

And as @hpaulj pointed out in a comment, it is useful to read all relevant documentation. Always prefer zeros over empty, unless you have a strong reason to do otherwise. From the docsting of empty:

Notes


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.

like image 153
Mike Müller Avatar answered Sep 16 '25 17:09

Mike Müller