I know how to compare 2 matrices of integers using Numpy. But does Numpy offer a way to get the list of elements that are different between them ?
Asked
Active
Viewed 71 times
1 Answers
2
Something like this?
>>> import numpy as np
>>> a = np.zeros(3)
>>> b = np.zeros(3)
>>> a[1] = 1
>>> a == b
array([ True, False, True], dtype=bool)
for floats: http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html
>>> np.isclose(a,b)
array([ True, False, True], dtype=bool)
indices of different elements
>>>[i for i,val in enumerate(np.isclose(a,b)) if val == False]
(using numpy instead)
>>> np.where(np.isclose(a,b) == False)
find values of different elements:
>>> d = [i for i,val in enumerate(np.isclose(a,b)) if val == False]
>>> a[d]
array([ 1.])
>>> b[d]
array([ 0.])

user3684792
- 2,542
- 2
- 18
- 23
-
Thank you. Is not the `for()` loop expensive for huge arrays ? Is not there some ready made function within Numpy ? – Feb 05 '15 at 15:52
-
it is a list comprehension not a for loop :) You could potentially use a map call instead, but it won't make that much of a difference http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map – user3684792 Feb 05 '15 at 15:58
-
maybe there is a better way in numpy, I will check – user3684792 Feb 05 '15 at 15:59