Introduction to Python NumPy Slicing

In This Article You Will Learn About Python Numpy Slicing.

Python Numpy Slicing – Before moving ahead, let’s know a little bit about Python Numpy Indexing.

Slicing in arrays

Slice in Python means to move elements from one index to another.

We use slice instead of the index as follows: [start: end].

It is also defined as the step by using this format: [start end; step].

If we fail to pass start, it is considered 0

If it doesn’t pass the end its length is the array’s dimension.

If we fail to pass step, it is considered 1

Example – Slicing the elements from index 2 to index 6 from the array.

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

print(Array[2:6])
Output - 

[3 4 5 6]

Note: It includes the starting index number, but excludes the ending index number.

Example – Slicing elements from index 2 to the ending element of the array.

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

print(Array[2:])
Output - 
[3 4 5 6 7]

Example – Slicing elements from beginning to index number 5.

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

print(Array[:6])
Output -

[1 2 3 4 5 6]

Negative Slicing

Use the minus operator to define an index from the ending point.

Example – Slicing from the index 4 from the end to index 2 from the end:

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

print(Array[-4:-2])
Output -

[4 5]

STEP

To determine the step value of the slicing, use the step value:

Example – Returning every 2nd element from index 1 to index 7.

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

print(Array[1:7:2])
Output -

[2 4 6]

Example – Returning every 2nd element from the whole array.

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

print(Array[::2])
Output - 

[1 3 5 7]

Slicing 2-D Arrays

Example – From the second element, slicing elements from index 1 to index 4.

import numpy as np
Array = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(Array[1, 1:4])
Output -

[7 8 9]

Note: Last index number is excluded.

Example – Returning index number 1’s element from an array.

import numpy as np
Array = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(Array[0:2, 1])
Output -

[2 7]

Example – From the arrays, slice index 0 to index 3 (not included), this will return a 2-D array:

import numpy as np
Array = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(Array[0:3, 0:3])
python-numPy-slicing

As a result, it returned an array containing from index 0 to index 3 (not included).

If you find anything incorrect in the above-discussed topic and have any further questions, please comment below.

Like us on

2 thoughts on “Introduction to Python NumPy Slicing”

Leave a Comment

Stay in the loop

codingstreets