WHAT IS ARRAY SLICING IN PYTHON NUMPY?

Accessing elements of an array from one given index to another given index is known as slicing in python.

Instead of passing index, we pass slice with step –

[start:end:step]

If we don’t pass start its considered 0

If we don’t pass end its considered length of array in that dimension

If we don’t pass step its considered 1

Example-

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

print(arr[1:3])
print(arr[3:]) 
print(arr[:3])
print(arr[-3:-1])
print(arr[1:4:2])
print(arr[::2])

Output

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

Explanation-

arr[1:3] – Slice elements from index 1 to index 3 from the array arr. The result is – [2 3], which includes the value available at start index 1, but excludes the end index 3.

arr[3: ] – Slice elements from index 3 to the end of the array arr.

arr[:3] – Slice elements from the beginning to index 3(not included)

arr[-3:-1] – Slice from the index 3 from the end to index 1 from the end

arr[1:4:2] – Here step value is 2, so it will return every other element from index 1 to index 4.

arr([::2]) – Return every other element from the entire array

Slicing 2-D Arrays

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[1, 1:3])
print(arr[0:2, 3])
print(arr[0:2, 1:3])

Output-

[7 8]
[4 9]
[[2 3]
 [7 8]]

Explanation-

arr[1, 1:3]- From the second element, slice elements from index 1 to index 3 (not included)

arr[0:2, 3]- From both elements, return index 3

arr[0:2, 1:3]- From both elements, slice index 1 to index 3(not included), this will return a 2-D array


Posted

in

Tags:

Comments

Leave a Reply