'python: Appending 2D and 3D array to make new 3D (bigger 3rd dimension)

I have two different arrays. A = [3124, 5] (representing 3124 models with 5 reference parameters) B = [3124, 19, 12288] (representing 3124 models, 19 time steps per model, 12288 temperature field data points per time step)

I want to add the same 5 values from A (parameter) array to the beginning of the temperature field array B for each time step, so that I end up with a new array AB = [3124, 19, 12293].

I have tried to use dstack AB = np.dstack((A, B)).shape

but I got the error message ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 19

Can anyone please help me?



Solution 1:[1]

With more modest shapes (your B is too big for my machine):

In [4]: A = np.ones((3,4)); B = 2*np.ones((3,5,133))

We can expand A to match with:

In [5]: A[:,None,:].shape
Out[5]: (3, 1, 4)
In [6]: A[:,None,:].repeat(5,1).shape
Out[6]: (3, 5, 4)

Now the arrays match on axis 0 and 1, all except the last joining one:

In [7]: AB=np.concatenate((A[:,None,:].repeat(5,1),B),axis=2)
In [8]: AB.shape
Out[8]: (3, 5, 137)

That corrects the problem raised in your error message:

ValueError: all the input array dimensions for the concatenation 
axis must match exactly, but along dimension 1, the array at 
index 0 has size 5 and the array at index 1 has size 19

Solution 2:[2]

Something like this will work:

import numpy

A = numpy.asarray([3124, 5])
B = numpy.asarray([3124, 19, 12288])

C = numpy.copy(B)

C[2] += A[1]

print(list(C))

output: [3124, 19, 12293]

However, you don't make it clear what your overarching objective is. The solution seems rather more direct than what you may want...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hpaulj
Solution 2 alvrm