What is the difference between ndarray and array in numpy?

前端 未结 5 1730
一个人的身影
一个人的身影 2020-11-28 01:27

What is the difference between ndarray and array in Numpy? And where can I find the implementations in the numpy source code?

5条回答
  •  时光取名叫无心
    2020-11-28 02:09

    numpy.ndarray() is a class, while numpy.array() is a method / function to create ndarray.

    In numpy docs if you want to create an array from ndarray class you can do it with 2 ways as quoted:

    1- using array(), zeros() or empty() methods: Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array.

    2- from ndarray class directly: There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

    The example below gives a random array because we didn't assign buffer value:

    np.ndarray(shape=(2,2), dtype=float, order='F', buffer=None)
    
    array([[ -1.13698227e+002,   4.25087011e-303],
           [  2.88528414e-306,   3.27025015e-309]])         #random
    

    another example is to assign array object to the buffer example:

    >>> np.ndarray((2,), buffer=np.array([1,2,3]),
    ...            offset=np.int_().itemsize,
    ...            dtype=int) # offset = 1*itemsize, i.e. skip first element
    array([2, 3])
    

    from above example we notice that we can't assign a list to "buffer" and we had to use numpy.array() to return ndarray object for the buffer

    Conclusion: use numpy.array() if you want to make a numpy.ndarray() object"

提交回复
热议问题