What is the numpy.take() Method in Python

Numpy.take() method “returns elements from the array along the mentioned axis and indices.”

Syntax

numpy.take(array, indices, axis = None, out = None, mode =’raise’)

Parameters

  1. array: This is the array on which we will work.
  2. indices: These are the indices of the values to be collected.
  3. axis: This field is optional. This is the axis over which we have to fetch the elements. Its default value is ‘None’; the array is flattened in this case.
  4. mode: There are three types of modes that work on how out-of-bound will work:
    1. raise: raise an error in case of out-of-bound
    2. warp: warp around
    3. clip: clip to the range

        Remember, this field is optional.

        Return Value

        The np.take() method returns an nD-array with the same type.

        Example 1: How to Use numpy.take() Method

        import numpy as np
        
        arr = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9), (50, 51, 52)])
        
        #Printing the array
        print("The array is: ")
        print(arr)
        
        #Printing values without mentioning axis
        indices = [2, 7]
        print("Values at position 2 and 7 are: ", np.take(arr, indices))
        
        #Printing valoues with axis
        indices = [0, 2]
        print("Values at position 0 and 2 are: \n", np.take(arr, indices, axis=1))

        Output

        The array is:
        [[ 1 2 3]
         [ 4 5 6]
         [ 7 8 9]
         [50 51 52]]
        Values at position 2 and 7 are: [3 8]
        Values at position 0 and 2 are:
         [[ 1 3]
         [ 4 6]
         [ 7 9]
         [50 52]]

        Example 2

        import numpy as np
        
        arr = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9), (50, 51, 52)])
        
        #Printing the array
        print("The array is: ")
        print(arr)
        
        #Printing values mode=warp
        indices = [0, 6]
        print("Values at position 0 and 6 are [mode=warp]:\n ",
         np.take(arr, indices, axis=1, mode='warp'))
        
        #Printing values mode=clip
        indices = [1, 5]
        print("Values at position 1 and 5 are [mode=clip]:\n ",
         np.take(arr, indices, axis=1, mode='clip'))
        
        #Printing values mode=raise
        indices = [2, 7]
        print("[mode=raise]:\n ", np.take(arr, indices, axis=1, mode='raise'))

        Output

        The array is:
        [[ 1 2 3]
         [ 4 5 6]
         [ 7 8 9]
         [50 51 52]]
        Values at position 0 and 6 are [mode=warp]:
         [[ 1 1]
         [ 4 4]
         [ 7 7]
         [50 50]]
        Values at position 1 and 5 are [mode=clip]:
         [[ 2 3]
         [ 5 6]
         [ 8 9]
         [51 52]]
        Traceback (most recent call last):
         
        IndexError: index 7 is out of bounds for size 3

        That’s it.

        Leave a Comment

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