Home > front end >  Adding a numpy array to another which has different dimensions
Adding a numpy array to another which has different dimensions

Time:05-23

I have an empty numpy array (let's call it a), which is for example (1200, 1000) in size.

There are several numpy arrays that I want to get sum of them and save them in the array a.

The size of these arrays (b_i) are like (1200, y), and y is max=1000.

Simply writing a code such as:

a = a   b_i

didn't work because of second dimension mismatch.

How can I solve that?

CodePudding user response:

The only idea I have with this is to start taking a sub-array of a with dimensions matching the b_i array and adding it that way. So something like this:

import numpy as np

a = np.zeros((12, 10))
b_1 = np.random.randint(1, 10, size=(12, 5))
b_2 = np.random.randint(1, 10, size=(12, 7))
b_3 = np.random.randint(1, 10, size=(12, 9))
arrs = [b_1, b_2, b_3]

for arr in arrs:
    a[:, :arr.shape[1]]  = arr

Or alternatively, as @BlackRaven had suggested you could instead pad the b_i with zeros to get it to the same shape as a.

CodePudding user response:

If you just want to concatinate arrays:

a = np.ones((1200,1000))
b = np.ones((1200, 500))
c = np.concatenate((a, b), axis=1)
c.shape # == (1200, 1500)

If you want elementwise addition, then reshape b to have the same dimentions as a

a = np.ones((1200,1000))
b = np.ones((1200, 500))
b_pad = np.zeros(a.shape)
b_pad[:b.shape[0],:b.shape[1]] = b
a   b_pad
array([[2., 2., 2., ..., 1., 1., 1.],
       [2., 2., 2., ..., 1., 1., 1.],
       [2., 2., 2., ..., 1., 1., 1.],
       ...,
       [2., 2., 2., ..., 1., 1., 1.],
       [2., 2., 2., ..., 1., 1., 1.],
       [2., 2., 2., ..., 1., 1., 1.]])

If you want a reusable function for this, then have a look at this question

  • Related