2
import numpy as np

I have two arrays of size n (to simplify, I use in this example n = 2):

A = array([[1,2,3],[1,2,3]])

B has two dimensions with n time a random integer: 1, 2 or 3.

Let's pretend:

B = array([[1],[3]])

What is the most pythonic way to subtract B from A in order to obtain C, C = array([2,3],[1,2]) ?

I tried to use np.subtract but due to the broadcasting rules I do not obtain C. I do not want to use mask or indices but element's values. I also tried to use np.delete, np.where without success. Thank you.

5
  • 1
    What if there are duplicates in any row of A? Commented Sep 14, 2018 at 13:32
  • In my case, there is no duplicate. But if there is let 's say substract the first iteration. Commented Sep 14, 2018 at 13:35
  • Check this link, hope it will help you out stackoverflow.com/questions/42557558/… Commented Sep 14, 2018 at 13:36
  • And what if no match is found? For ex. : B = array([[5],[3]])? Commented Sep 14, 2018 at 13:38
  • In my case, there will alway be a match. Commented Sep 14, 2018 at 13:45

1 Answer 1

1

This might work and should be quite Pythonic:

dd=[[val for val in A[i] if val not in B[i]] for i in xrange(len(A))]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It does work with 'range' instead of 'xrange'.
I am still using Python2.X, therefore xrange... Glad it worked!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.