yny
yny

Reputation: 90

Find index of changing value between two arrays

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

Upvotes: 3

Views: 1767

Answers (5)

Sundara Kesavan
Sundara Kesavan

Reputation: 149

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]

Upvotes: 2

xashru
xashru

Reputation: 3580

You can use numpy's where function to do this

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

Upvotes: 3

sangram desai
sangram desai

Reputation: 31

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

Upvotes: 0

jpp
jpp

Reputation: 164703

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)

Upvotes: 3

Austin
Austin

Reputation: 26039

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]

Upvotes: 2

Related Questions