0

I have two NumPy array below:

my_array1 = [np.array([[1, 2, 3],
                      [4, 5, 6],
                      [7, 8, 9]]), 
             np.array([[10],
                      [13],
                      [15]])]
my_array2 = [np.array([[3, 2, 1],
                      [6, 5, 4],
                      [9, 8, 7]]), 
             np.array([[7],
                      [8],
                      [9]])]

I want to calcualte my_array1 - my_array2 as below:

my_want = [np.array([[-2, 0, 2],
                      [-2, 0, 2],
                      [-2, 0, 2]]), 
           np.array([[3],
                     [5],
                     [6]])]

Is there an elegant way to do it in python?

3
  • [a1 - a2 for a1, a2 in zip(my_array1, my_array2)] or list(map(operator.sub, my_array1, my_array2)) Commented Oct 2, 2022 at 4:33
  • What I know is [my_array1[i] - my_array2[i] for i in range(len(my_array2))] Commented Oct 2, 2022 at 4:34
  • my_array is not an array, it is a list Commented Oct 2, 2022 at 5:22

2 Answers 2

2
delta = [i-j for i,j in zip(my_array1,my_array2)]
print(delta)
[array([[-2,  0,  2],
       [-2,  0,  2],
       [-2,  0,  2]]), array([[3],
       [5],
       [6]])]
Sign up to request clarification or add additional context in comments.

Comments

0

It looks like not two, but four NumPy arrays, packed into native lists

my_want = []
for index in range(2):
    my_want.append(my_array1[index] - my_array2[index])
>>> my_want
[array([[-2,  0,  2],
       [-2,  0,  2],
       [-2,  0,  2]]), array([[3],
       [5],
       [6]])]

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.