The difference can be demonstrated by this example:
generate a matrix
>>> A = numpy.matrix(numpy.ones((3,3)))
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.array
to modify A
. Doesn't work because you are modifying a copy
>>> numpy.array(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.asarray
to modify A
. It worked because you are modifying A
itself
>>> numpy.asarray(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Hope this helps!
Here's a simple example that can demonstrate the difference.
The main difference is that array will make a copy of the original data and using different object we can modify the data in the original array.
import numpy as np
a = np.arange(0.0, 10.2, 0.12)
int_cvr = np.asarray(a, dtype = np.int64)
The contents in array (a), remain untouched, and still, we can perform any operation on the data using another object without modifying the content in original array.
The differences are mentioned quite clearly in the documentation of array
and asarray
. The differences lie in the argument list and hence the action of the function depending on those parameters.
The function definitions are :
numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
and
numpy.asarray(a, dtype=None, order=None)
The following arguments are those that may be passed to array
and not asarray
as mentioned in the documentation :
copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if
__array__
returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).
ndmin : int, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
asarray(x)
is like array(x, copy=False)
Use asarray(x)
when you want to ensure that x
will be an array before any other operations are done. If x
is already an array then no copy would be done. It would not cause a redundant performance hit.
Here is an example of a function that ensure x
is converted into an array first.
def mysum(x):
return np.asarray(x).sum()
The definition of asarray
is:
def asarray(a, dtype=None, order=None):
return array(a, dtype, copy=False, order=order)
So it is like array
, except it has fewer options, and copy=False
. array
has copy=True
by default.
The main difference is that array
(by default) will make a copy of the object, while asarray
will not unless necessary.
Source: Stackoverflow.com