What is the difference between Numpy's array() and asarray() functions?

前端 未结 6 787
孤城傲影
孤城傲影 2020-11-28 00:52

What is the difference between Numpy\'s array() and asarray() functions? When should you use one rather than the other? They seem to generate identical output for all the in

6条回答
  •  情深已故
    2020-11-28 01:15

    The difference can be demonstrated by this example:

    1. generate a matrix

      >>> A = numpy.matrix(numpy.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.]])
      

    Hope this helps!

提交回复
热议问题