Adding a 1-D Array to a 3-D array in Numpy
Asked Answered
S

3

6

I am attempting to add two arrays.

np.zeros((6,9,20)) + np.array([1,2,3,4,5,6,7,8,9])

I want to get something out that is like

array([[[ 1.,  1.,  1., ...,  1.,  1.,  1.],
        [ 2.,  2.,  2., ...,  2.,  2.,  2.],
        [ 3.,  3.,  3., ...,  3.,  3.,  3.],
        ..., 
        [ 7.,  7.,  7., ...,  7.,  7.,  7.],
        [ 8.,  8.,  8., ...,  8.,  8.,  8.],
        [ 9.,  9.,  9., ...,  9.,  9.,  9.]],

       [[ 1.,  1.,  1., ...,  1.,  1.,  1.],
        [ 2.,  2.,  2., ...,  2.,  2.,  2.],
        [ 3.,  3.,  3., ...,  3.,  3.,  3.],
        ..., 
        [ 7.,  7.,  7., ...,  7.,  7.,  7.],
        [ 8.,  8.,  8., ...,  8.,  8.,  8.],
        [ 9.,  9.,  9., ...,  9.,  9.,  9.]],

So adding entries to each of the matrices at the corresponding column. I know I can code it in a loop of some sort, but I am trying to use a more elegant / faster solution.

Sirree answered 29/8, 2015 at 7:26 Comment(3)
What must be the shape of output array?Socinian
For this example, it would need to retain the shape of the 3-D array, so 6,9,20Sirree
You won't get an output like array([[[ 1., 2., 3., ..., 7., 8., 9.],... with that shape (6,9,20), because the last dimension in desired output seems to have 9 elements and not 20.Socinian
S
6

You can bring broadcasting into play after extending the dimensions of the second array with None or np.newaxis, like so -

np.zeros((6,9,20))+np.array([1,2,3,4,5,6,7,8,9])[None,:,None]
Socinian answered 29/8, 2015 at 7:40 Comment(0)
J
4

If I understand you correctly, the best thing to use is NumPy's Broadcasting. You can get what you want with the following:

np.zeros((6,9,20))+np.array([1,2,3,4,5,6,7,8,9]).reshape((1,9,1))

I prefer using the reshape method to using slice notation for the indices the way Divakar shows, because I've done a fair bit of work manipulating shapes as variables, and it's a bit easier to pass around tuples in variables than slices. You can also do things like this:

array1.reshape(array2.shape)

By the way, if you're really looking for something as simple as an array that runs from 0 to N-1 along an axis, check out mgrid. You can get your above output with just

np.mgrid[0:6,1:10,0:20][1]
Jennefer answered 29/8, 2015 at 8:2 Comment(0)
F
0

You could use tile (but you would also need swapaxes to get the correct shape).

A = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
B = np.tile(A, (6, 20, 1))
C = np.swapaxes(B, 1, 2)
Floreated answered 29/8, 2015 at 7:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.