Indexing and slicing arrays in python numpy

               Indexing is the process of retrieving specific elements, whereas slicing extracts subarrays in a range. Both methods support negative indices and returns the original array elements.

Mainly, these two methods make the user to access, extract the elements and manipulates the array in efficient manner. Let us discuss the methods with sample code as follows…

Indexing in Numpy:

              It supports three methods as follows.

  • ·       Single element indexing
  • ·       Multi-dimensional indexing
  • ·       Index arrays

The sample code is given below..

Single element indexing:

              It follows list concept in python.

Code:

import numpy as np1

s_arr = np1.arange(10)   # [0,1,2,3,4,5,6,7,8,9]

print(s_arr[3])  

print(s_arr[-2]) 

Output:

3

8

Multi-dimensional indexing:

              It follows two dimensional arrays.

import numpy as np1

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

print(s_arr2d[1,2])  

print(s_arr2d[0])

Output:

66

[11 22 33]

Index arrays:

import numpy as np1

s_arr = np1.arange(10,1,-2)   # [1,8,6,4,2]

print(s_arr[[3,1,2]])      

output:

[4,8,6]

Slicing in python:

o   It has three types are as follows.

  • ·       Negative indices
  • ·       Multidimensional slicing
  • ·       Ellipsis

 Syntax:

 arr[start:stop:step]

    • start: inclusive
    • stop: exclusive
    • step: stride (default = 1)

let us create the code.

Code:

import numpy as np1

s_arr = np1.arange(10)   # [0,1,2,3,4,5,6,7,8,9]

print("Slicing from 2 nd to 7",s_arr[2:7])     

print("Slicing from 5th element",s_arr[:5])      

print("Slicing from 2nd element",s_arr[::2])     

print("Slicing from -1 element",s_arr[::-1])

Output:

Slicing from 2 nd to 7 [2 3 4 5 6]

Slicing from 5th element [0 1 2 3 4]

Slicing from 2nd element [0 2 4 6 8]

Slicing from -1 element [9 8 7 6 5 4 3 2 1 0]

Negative indices:

It Counts from the end.

Code:

import numpy as np1

s_arr = np1.arange(10)   # [0,1,2,3,4,5,6,7,8,9]

print("Slicing from -1 element",s_arr[::-1]) 

Output:

Slicing from -1 element [9 8 7 6 5 4 3 2 1 0]

Multi-dimensional slicing:

import numpy as np1

s_arr2d = np1.arange(12).reshape(3,4)

print(s_arr2d[1:, :2])

Output:

[[4 5]

 [8 9]]

Ellipsis (...):

 It represents all dimensions.

Code:

import numpy as np1

s_arr3d = np1.arange(27).reshape(3,3,3)

print(s_arr3d[...,1])

Output:

[[ 1  4  7]

 [10 13 16]

 [19 22 25]]

These are the ways to implement slicing and indexing in numpy using Python. 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