举例说明Numpy的数组属性

129 阅读1分钟

NumPy数组有一些有用的属性,可以帮助你轻松使用它。本文将向你展示一些如何正确使用它们的例子。

1.常见的NumPy数组属性

  1. ndarray.flags。返回ndarray数组的内存信息,如数组的存储方式,是否是其他数组的拷贝。

    >>> import numpy as np
    >>> 
    >>> arr = np.array(['python', 'java', 'javascript'])
    >>> 
    >>> print(arr.flags)
      C_CONTIGUOUS : True
      F_CONTIGUOUS : True
      OWNDATA : True
      WRITEABLE : True
      ALIGNED : True
      WRITEBACKIFCOPY : False
      UPDATEIFCOPY : False
    
    
  2. ndarray.itemsize:返回数组中每个元素的大小,单位是字节。

    >>> import numpy as np
    >>> 
    >>> arr = np.array(['python', 'java', 'javascript'])
    >>>
    >>> print(arr.itemsize)
    40
    >>> 
    >>> arr1 = np.array([6, 7, 8, 9, 10], dtype = np.int8)
    >>> 
    >>> print(arr1.itemsize)
    1
    
    
  3. ndarray.ndim:返回数组的尺寸。

    >>> import numpy as np
    >>>
    >>> arr1 = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
    >>> 
    >>> print(arr1.ndim)
    2
    
    
  4. ndarray.shape:shape属性的返回值是一个由数组尺寸组成的元组。例如,一个有2行3列的二维数组可以表示为(2,3)。这个属性可以用来调整数组尺寸的大小。

    >>> import numpy as np
    >>>
    # create the Numpy array.
    >>> arr1 = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
    >>> 
    # print it's dimension.
    >>> print(arr1.ndim)
    2
    # print the NumPy array shape.
    >>> print(arr1.shape)
    (3, 3)
    >>>
    # change the NumPy array shape.
    >>> arr1.shape = (1, 9)
    >>> 
    # print the reshaped array.
    >>> print(arr1)
    [[1 2 3 4 5 6 7 8 9]]
    
    
  5. ndarray.reshape():该方法用于调整数组的形状。

    >>> import numpy as np
    >>>
    # create the original 2 dimension array.
    >>> arr1 = np.array([[1, 2, 3],[4, 5, 6]]) 
    >>> 
    # print out the array shape.
    >>> print(arr1.shape)
    (2, 3)
    >>> 
    # reshape the above array to (3,2)
    >>> arr1.reshape(3, 2)
    array([[1, 2],
           [3, 4],
           [5, 6]])
    >>> 
    # you can find that the original array's shape is not changed.
    >>> print(arr1)
    [[1 2 3]
     [4 5 6]]