Home > OS >  How to subtract the two different numpy array with the same dimension
How to subtract the two different numpy array with the same dimension

Time:10-02

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?

CodePudding user response:

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

CodePudding user response:

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]])]
  • Related