How to find the groups of consecutive elements in a NumPy array?

Learn, how to find the groups of consecutive elements in a NumPy array in Python? By Pranit Sharma Last updated : September 18, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose we are given a NumPy array containing some randomly ordered integer values but also some values are consecutive to each other. We need to find the groups of consecutive elements in this array.

Finding the groups of consecutive elements in a NumPy array

For this purpose, it would be better to define a function so that we can perform the check on each element of the array. We will use numpy.where() and return the group of those elements which are consecutive.

Let us understand with the help of an example,

Python program to find the groups of consecutive elements in a NumPy array

# Import numpy
import numpy as np

# Creating numpy array
arr = np.array([52,53,99,100,10,30])

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

# defining a function to check values
def fun(data):
    return np.split(data, np.where(np.diff(data) != 1)[0]+1)

# Calling function
res = fun(arr)

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

Output

The output of the above program is:

Example: How to find the groups of consecutive elements in a NumPy array?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





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