Sunday, March 4, 2018

numpy.array vs numpy.asarray

Looking at the definition, you'll see the difference between them:
def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)
The main difference is that array (by default) will make a copy of the object, while asarray will not unless necessary.

The difference can be demonstrated by this example:
  1. generate a matrix
    >>> A = numpy.matrix(np.ones((3,3)))
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
  2. 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.]])
  3. 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.]])

No comments: