Fancy indexing with a list of indices in python

                              It is one of the advanced indexing methods in Numpy. It makes you to find arbitrary elements in the list or array of index. Let us implement in different ways.

  • ·       1D array
  • ·       Reordering the elements of 1D array
  • ·       2D array
  • ·       Selecting specific elements

👉1D array:

              This deals with Single dimensional array. First, it reads the array elements. Find the arbitrary elements. Finally, print the output.

Code:

import numpy as np1

s_arr = np1.array([11, 22, 33, 44, 55, 66, 77])

indices = [0, 2, 4]

result = s_arr[indices]

print("The indices are:",result)

Output:

The indices are: [11 33 55]

👉Reordering the elements of 1D array:

              It Rearranges the indices in this program.

Code:

import numpy as np1

s_arr = np1.array([11, 22, 33, 44, 55, 66, 77])

print("The Rearrangement of indices are:",s_arr[[4, 2, 0]])

Output:

The Rearrangement of indices are: [55 33 11]

👉2D array:

              This program creates a 2D array with elements. It selects a set of rows. Finally, it displays the output.

Code:

import numpy as np1

s_arr = np1.array([

    [1, 2],

    [4, 3],

    [5, 6],

    [8, 7]

])

rows = [0, 1, 3]

print("Here , is the fancy indices:\n",s_arr[rows])

Output:

Here , is the fancy indices:

 [[1 2]

 [4 3]

 [8 7]]

👉Selecting specific elements in 2D array:

              This program selects the specific elements from the array.

Code:

import numpy as np1

s_arr = np1.array([

    [11, 22, 33],

    [44, 55, 66],

    [77, 88, 99]

])

print("This is the selection of specific elements:\n",s_arr[[0, 1, 2], [2, 1, 0]])

Output:

This is the selection of specific elements:

 [33 55 77]

These are the various methods to find fancy indices in python using numpy. Hope, you understood the concept. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Datatypes and Variables in java script