Index multiple, non-adjacent ranges in NumPy?

Learn, how to index multiple non adjacent ranges in Python NumPy?
By Pranit Sharma Last updated : December 25, 2023

Problem statement

Suppose that we are given a numpy array and we need to select multiple and non-adjacent ranges from this array.

For example, if we are given an array as [1,2,3,4,5,6,7,8,9,10] and we need to select multiple ranges like [0:3] and [4:6] and [7:].

Indexing multiple non-adjacent ranges

To index multiple, non-adjacent ranges, we need to concatenate, either before or after indexing. Numpy provides a good function called numpy.r_() which is used to concatenate multiple sliced values along the 1st axis.

Let us understand with the help of an example,

Python code to index multiple, non-adjacent ranges in NumPy

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([0, 1, 2, 3,4, 5, 6, 7])

# Display Original array
print("Original array:\n",arr,"\n")

# Multiple, non-adjacent slicing
res = np.r_[0:3,4:6,7:]

# Display result
print("Result:\n",res,"\n")

Output

Example: Index multiple, non-adjacent ranges in NumPy?

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.