3

Can I find the index of the changed value by comparing two arrays?

For exaple;

array1 = [1, 2 ,3]
array2 = [1, 2, 4]

I want to find the index of the changing value by comparing these two arrays. For this example this should be 2.

I am using numpy to compare two arrays. But I can't find the index of changed value(s).

0

5 Answers 5

3

Since you are using NumPy, you can compare using the != operator and use np.flatnonzero:

array1 = np.array([1,2,3])
array2 = np.array([1,2,4])

res = np.flatnonzero(array1 != array2)

print(res)
# array([2], dtype=int64)
Sign up to request clarification or add additional context in comments.

Comments

3

You can use numpy's where function to do this

array3 = np.where((array1-array2) != 0)

Comments

2

This is a non-numpy solution. You can use enumerate() with zip():

array1 = [1,2,3]
array2 = [1,2,4]

print([i for i, (x, y) in enumerate(zip(array1, array2)) if x != y])
# [2]

Comments

2

To find index of n changing elements between two lists we can use

c = set(a) - set(b)
[a.index(i) for i in c]

1 Comment

This doesn't work. It can find the wrong index if the same element can occur twice. It also doesn't work if the lists have the same element in different positions. Even when it works, this is very inefficient. It requires a loop (the index call) per mismatching element.
0

list(set(a1)-set(a2)) gives the list of all the elements which are not present in the set a2

a1 = [1,2,3]
a2 = [1,2,4]
arr=list(set(a1)-set(a2)) #arr=[3]
print(a1.index(arr[0]))   #2

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.