1

How would I go about comparing two different numpy arrays to create a third array? I want to write a loop that goes through two arrays and prints a new array "c" with only the values that are not in a or b

For example say I have

a = [1,2,3,4]
b = [1,2,3,4,5,6,7,8,9]

I want it to print:

c = [5,6,7,8,9]
Jan
  • 42,290
  • 8
  • 54
  • 79
cryptofish
  • 89
  • 8

1 Answers1

3

You can use set difference operation in Numpy: numpy.setdiff1d. From the Numpy docs:

>>> a = np.array([1, 2, 3, 2, 4, 1])
>>> b = np.array([3, 4, 5, 6])
>>> np.setdiff1d(a, b)
array([1, 2])
athul.sure
  • 328
  • 5
  • 14
  • 1
    Might be worth pointing out explicitly (though the example from docs is crafted well enough to show implicitly) that `setdiff1d` doesn't care about repetition in the array. Welcome to Stack Overflow! – alkasm Jun 21 '17 at 17:09
  • Thank you so much! – cryptofish Jun 21 '17 at 17:14
  • The OP does specify which array should be subtracted from the other. It seems he wants all unique values in either array: `a = np.array([1, 2, 3, 2, 4, 1]) b = np.array([3, 4, 5, 6]) c = np.concatenate((np.setdiff1d(a, b), np.setdiff1d(b,a)))` – jack6e Jun 21 '17 at 17:40