Bea GA M
Bea GA M

Reputation: 23

How to get the indexes of where the values of an array are different in python

I have an array that looks like (simplified version):

[14 14 14 14 14 13 13 13 13 13 2 2 2 2 2 2 2 2 2]

What I need to do is to identify the index where it changes. Like index 5 is 13 and so on. I do not know how to do this. Any kind of help is welcomed!! :)

I've tried it with np.unique, but the output of this sorts the numbers ascending, so I lose where the numbers actually change.

Upvotes: 2

Views: 1130

Answers (5)

Anurag Dhadse
Anurag Dhadse

Reputation: 1873

This is fastest way possible to find the unique number index change.

import numpy as np

arr = np.array([14, 14, 14, 13, 20, 20, 20, 2, 2, 2])

np.unique(arr, return_index=True)

Output

(array([ 2, 13, 14, 20]), array([7, 3, 0, 4]))

Upvotes: 0

Oli
Oli

Reputation: 2602

You can compare each item in the array with the next item using a[1:]!=a[:-1] (for some 1d array a). You can then convert this array of booleans to indices by using np.where. Because of the slicing, you need to add one to this.

# added a 4 to the end of the array to have an extra place where the number changes
a=np.array([14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 2, 2, 2, 2, 2, 2, 2, 2, 2,4])
changes = np.where(a[1:]!=a[:-1])[0]+1
print('change indices:',changes)
print('before each change:',a[changes-1])
print('after each change:',a[changes])

This outputs:

change indices: [ 5 10 19]
before each change: [14 13  2]
after each change: [13  2  4]

Upvotes: 1

Be Chiller Too
Be Chiller Too

Reputation: 2900

Pythonic way, using a list comprehension:

arr=[15,14,14,14,14,14,13,13,13,13,13,2,2,2,2,2,2,2,2,2,3]                                   

[i+1 for i in range(len(arr)-1) if arr[i] != arr[i+1]]                                        
# >>> [1, 6, 11, 20]

Upvotes: 2

Muhammad Safwan
Muhammad Safwan

Reputation: 1024

It very simple use a loop

all_indexes = []
lisst = [14,14, 14, 14, 14, 13, 13, 13, 13, 13, 2, 2 ,2, 2, 2, 2, 2, 2, 2]
for i in range(len(lisst)-1):
    if lisst[i] != lisst[i+1]:
        all_indexes.append(i+1)
        
        
print(all_indexes)

Upvotes: -1

Davinder Singh
Davinder Singh

Reputation: 2162

Check out this code :

arr = [14,14,14,14,14,13,13,13,13,13,2,2,2,2,2,2,2,2,2]
k = arr[0]
for i, j in enumerate(arr):
    if k != j:
        print(i) 
    k = arr[i]

OUTPUT:

5
10

Upvotes: -1

Related Questions