I am looking for some examples which shows the difference between numpy.asanyarray()
and numpy.asarray()
? And at which conditions should I use specifically asanyarray()?
The main difference is that array (by default) will make a copy of the object, while asarray will not unless necessary.
asarray() function is used when we want to convert input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays. Syntax : numpy.asarray(arr, dtype=None, order=None)
array is just a convenience function to create an ndarray ; it is not a class itself. You can also create an array using numpy. ndarray , but it is not the recommended way. From the docstring of numpy.
Code for asanyarray
:
return array(a, dtype, copy=False, order=order, subok=True)
for asarray
:
return array(a, dtype, copy=False, order=order)
The only difference is in specifying the subok
parameter. If you are working with subclasses of ndarray
you might want to use it. If you don't know what that means, it probably doesn't matter.
The defaults for np.array
are:
array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
If you are fine tuning a function that is supposed to work with all kinds of numpy arrays (and lists that can be made into arrays), and shouldn't make unnecessary copies, you can use one of these functions. Otherwise np.array
, without or without the extra prameters, works just fine. As a beginner don't put much effort into understanding these differences.
===
expand_dims
uses both:
if isinstance(a, matrix):
a = asarray(a)
else:
a = asanyarray(a)
A np.matrix
subclass array can only have 2 dimensions, but expand_dims
has to change that, so uses asarray
to turn the input into a regular ndarray
. Otherwise it uses asanyarray
. That way a subclass like maskedArray remains that class.
In [158]: np.expand_dims(np.eye(2),1)
Out[158]:
array([[[1., 0.]],
[[0., 1.]]])
In [159]: np.expand_dims(np.matrix(np.eye(2)),1)
Out[159]:
array([[[1., 0.]],
[[0., 1.]]])
In [160]: np.expand_dims(np.ma.masked_array(np.eye(2)),1)
Out[160]:
masked_array(
data=[[[1., 0.]],
[[0., 1.]]],
mask=False,
fill_value=1e+20)
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