Numpy Array Properties Example

The NumPy array has some useful properties that can help you to use it easily. This article will show you some examples of how to use them correctly.

1. Common NumPy Array Properties.

  1. ndarray.flags: Returns the memory information of the ndarray array, such as the storage method of the array and whether it is a copy of other arrays.
    >>> 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: Returns the size of each element in the array in bytes.
    >>> 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: Returns the dimension of the array.
    >>> import numpy as np
    >>>
    >>> arr1 = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
    >>> 
    >>> print(arr1.ndim)
    2
    
  4. ndarray.shape: The return value of the shape property is a tuple composed of array dimensions. For example, a two-dimensional array with 2 rows and 3 columns can be expressed as (2,3). This property can be used to adjust the size of array dimensions.
    >>> 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(): This method is used to adjust the array shape.
    >>> 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]]

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.