How to find index where elements change value NumPy?

Learn, how to find index where elements change value NumPy in Python? By Pranit Sharma Last updated : December 23, 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 that we are given a NumPy array that contains the same elements, however, there are some different values at certain positions, we need to find an efficient way to know the index where the values of this array change.

NumPy - Finding index where elements change value

For this purpose, we can simply use a for loop over the array and compare each value with its neighbor and return its index if the values do not match. Append these indices to a list using the list.append() method and then print it.

Let us understand with the help of an example,

Python code to find index where elements change value NumPy

# Import numpy
import numpy as np

# Creating a numpy array
arr = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 3, 4, 3, 4, 3, 4, 5, 5, 5]

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

# Finding the indices
l = []
for i in range(len(arr)-1):
    if arr[i]!=arr[i+1]:
        l.append(i)

# Display indices
print("Indices:\n",l,"\n")

Output

Example: How to find index where elements change value NumPy?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





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