Selecting a sub array from a NumPy array (Slicing)

To get a sub-array, we pass a slice in place of the element index.

Syntax:

numpyArr[x:y]

Here x and y are the starting and last index of the required sub-array.

Example:

Python3




import numpy as np
  
# NumPy Array
numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
  
# the slice 3:6 is passed instead 
# of index
print("Sub-Array=", numpyArr[3:6])


Output:

Sub-Array= [4 5 6]

A sub-array starting from the 3rd index up to the 6th index ( excluding the last the 6th index ) was selected. You can slice a sub-array starting from the first element by leaving the starting index blank.

Example: The following code selects a sub-array starting from the first element. 

Python3




import numpy as np
  
numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
  
# works same as 0:6
print("Sub-Array=", numpyArr[:6])


Output:

Sub-Array= [1 2 3 4 5 6]

Similarly, leaving the left side of the colon blank will give you an array up to the last element.

Example: The following code selects a sub-array starting from a particular index up to the last index.

Python3




import numpy as np
  
numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
  
# same as 3:9 or 3:n, where n is
# the length of array
print("Sub-Array=", numpyArr[3:])


Output:

Sub-Array= [4 5 6 7 8 9]


Select an element or sub array by index from a Numpy Array

The elements of a NumPy array are indexed just like normal arrays. The index of the first element will be 0 and the last element will be indexed n-1, where n is the total number of elements.

Similar Reads

Selecting a single element from a NumPy array

Each element of these ndarrays can be accessed using its index number....

Selecting a sub array from a NumPy array (Slicing)

...