2

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.

1
  • Thanks to everyone who helped! I finally got to solve my issue. Commented May 29, 2021 at 12:07

5 Answers 5

2

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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]

1 Comment

Big thanks!! This worked!! It's similar to another posted and both worked. Thanks!!
0

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]))

1 Comment

np.unique shows the values sorted, so it does not solve what I wanted to achieve.
-1

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

Comments

-1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.