What is the difference between Numpy's array() and asarray() functions?
The definition of
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=True by default.
The main difference is that
array (by default) will make a copy of the object, while
asarray will not unless necessary.
Since other questions are being redirected to this one which ask about
asanyarray or other array creation routines, it's probably worth having a brief summary of what each of them does.
The differences are mainly about when to return the input unchanged, as opposed to making a new array as a copy.
array offers a wide variety of options (most of the other functions are thin wrappers around it), including flags to determine when to copy. A full explanation would take just as long as the docs (see Array Creation, but briefly, here are some examples:
a is an
m is a
matrix, and they both have a
np.array(m)will copy both, because that's the default behavior.
np.array(m, copy=False)will copy
mis not an
np.array(a, copy=False, subok=True)and
np.array(m, copy=False, subok=True)will copy neither, because
matrix, which is a subclass of
np.array(a, dtype=int, copy=False, subok=True)will copy both, because the
dtypeis not compatible.
Most of the other functions are thin wrappers around
array that control when copying happens:
asarray: The input will be returned uncopied iff it's a compatible
asanyarray: The input will be returned uncopied iff it's a compatible
ndarrayor subclass like
ascontiguousarray: The input will be returned uncopied iff it's a compatible
ndarrayin contiguous C order (
asfortranarray: The input will be returned uncopied iff it's a compatible
ndarrayin contiguous Fortran order (
require: The input will be returned uncopied iff it's compatible with the specified requirements string.
copy: The input is always copied.
fromiter: The input is treated as an iterable (so, e.g., you can construct an array from an iterator's elements, instead of an
objectarray with the iterator); always copied.
There are also convenience functions, like
asarray_chkfinite (same copying rules as
asarray, but raises
ValueError if there are any
inf values), and constructors for subclasses like
matrix or for special cases like record arrays, and of course the actual
ndarray constructor (which lets you create an array directly out of strides over a buffer).
The difference can be demonstrated by this example:
generate a matrix
3,3))) Amatrix([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])A = numpy.matrix(numpy.ones((
A. Doesn't work because you are modifying a copy
2]=2Amatrix([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])numpy.array(A)[
A. It worked because you are modifying
2]=2Amatrix([[ 1., 1., 1.], [ 1., 1., 1.], [ 2., 2., 2.]])numpy.asarray(A)[
Hope this helps!