NumPy – Array Slicing

Slicing the array in a range from start to end is what we call Array Slicing. Slice (range) is passed in place of index i.e.

n[1:3]

The above will slice two elements from index 1 to index 3 because it includes the start index, but excludes the end index.

The following is the syntax to slice NumPy arrays:

arr[start:end]

Here, the start is the beginning index (include), and the end is the last index (excluded)

Slicing Examples

The following Array Slicing examples we will run:

  • Slicing from index 1 to 3 (3 is excluded)
  • Slicing from index 2 to 5 (5 is excluded)
  • Slicing from index 5 to last
  • Slicing from the beginning to index 5 (5 is excluded)

Example: Slicing from index 1 to 3 (3 is excluded)

import numpy as np

n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65])
print(n[1:3])

Output

[25 30]

Example: Slicing from index 2 to 5 (5 is excluded)

import numpy as np

n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65])
print(n[2:5])

Output

[30 35 40]

Example: Slicing from index 5 to last

import numpy as np

n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65])
print(n[5:])

Output

[45 50 55 60, 65]

Example: Slicing from beginning to index 5 (5 is excluded)

import numpy as np

n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65])
print(n[:5])

Output

[20 25 30 35 40]

Slice 1D arrays with STEP

We can also include steps while slicing. Step means a jump of elements. If the step is 2, that means 2 jumps for the next element.

Syntax

arr[start:end:step}

Example

import numpy as np

n = np.array([5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60])
print(n[1:10:2])

Output

[10 20 30 40 50]

Slicing 2D arrays with STEP

The following are the examples of slicing Two-Dimensional arrays with steps:

Example: Slicing from index 2 to 5 (excluding 5)

import numpy as np
   
n = np.array([[10,30,50,70,90,95],[4,8,12,14,16,18]])
print(n[0,2:5])

Output

[50 70 90]

Example: Slicing for both the dimensions with step

import numpy as np

n = np.array([[10, 30, 50, 70, 90, 95], [4, 8, 12, 14, 16, 18]])
print(n[0:2, 2:5])

Output

[[50 70 90]
 [12 14 16]]

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.

For Videos, Join Our YouTube Channel: Join Now


Read More:

Array Indexing
Datatypes in Numpy
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment