NumPy - Basic Indexing & Slicing

The items of an array can be accessed and assigned to the same way as other Python sequences (e.g. lists).
Items in ndarray object follows zero-based index.

Indexing

Three types of indexing methods are available −
1. Field access
2. Basic slicing
3. Advanced indexing.

1. Field access

Example 1: Accessing an Element

import numpy as np 
a = np.arange(10)

print("NumPy array is ",a)
print("Element at mentioned index is",a[5]) 

Output:
NumPy array is  [0 1 2 3 4 5 6 7 8 9]
Element at mentioned index is 5

Example 2: Using start, end (exclusive), step

import numpy as np 
b = np.arange(10, 30, 2) 

print("NumPy array is ",b)
print("Element at mentioned index is",b[5]) 

Output:
NumPy array is  [10 12 14 16 18 20 22 24 26 28]
Element at mentioned index is 20

Example 3: For multidimensional arrays, indexes are tuples of integers

import numpy as np 
c = np.array([[1,2,3], [4,5,6]])

#print the array
print(c)

# Note: first array/column starts at 0.
# Accessing elements using row , column index 
print(c[0, 2])
print(c[1, 1])

Output:
[[1 2 3]
 [4 5 6]]
3
5

Example 4: Assigning or Updating the value

c[1, 1] = 10
print(c)

Output:
[[ 1  2  3]
 [ 4 10  6]]

2. Basic Slicing

Basic slicing is an extension of Python's basic concept of slicing to n dimensions.
A Python slice object is constructed by giving start, stop, and step parameters to the built-in slice function. This slice object is passed to the array to extract a part of array.

Creating NumPy Arrays

import numpy as np 
a = np.arange(10)
print(a)

Output:
[0 1 2 3 4 5 6 7 8 9]

Example 1: Using Startindex: Endindex(exclusive)

# Slicing the elements from index 1 to 5 
print(a[1:5])

Output:
[1 2 3 4]

Example 2: Using Startindex: Endindex(exclusive) : Step

# Slicing the elements using Step
print(a[1:9:2])

Output:
[1 3 5 7]

Example 3: Alternative Ways of slicing with default values

#End index is not mentioned
print(a[1:])

#Start index is not mentioned 
print(a[:9])

Output:
[1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8]

Example 4: Assigning and slicing the elements

#Array creation
import numpy as np 
b = np.arange(10)
print(b)

# Assigning the value
b[5:] = 20
print(b)

#Slicing 
print(b[3:7])

Output:
[0 1 2 3 4 5 6 7 8 9]
[ 0  1  2  3  4 20 20 20 20 20]
[ 3  4 20 20]

Using Ellipsis (…)

Slicing can also include ellipsis (…) to make a selection tuple of the same length as the dimension of an array. If ellipsis is used at the row position, it will return an ndarray comprising of items in rows.

Example 5: Using Ellipsis

import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 
print(a)  

# Slice all items from the second row
print(a[1,...])

# Slice all items from second column 
print(a[...,1])

Output:
[[1 2 3]
 [3 4 5]
 [4 5 6]]
[3 4 5]
[2 4 5]
Total Website Visits: 40430
© Copyright 2018 - 2020. All Rights Reserved.

Developed by Vinoth Rathinam