Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a 1-D Array to a 3-D array in Numpy

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.

like image 244
psh5017 Avatar asked Aug 29 '15 07:08

psh5017


People also ask

How can I add 1D array in NumPy?

Use append() to add an element to Numpy Array. Use concatenate() to add an element to Numpy Array. Use insert() to add an element to Numpy Array.

Can you combine NumPy arrays?

Joining NumPy Arrays Joining means putting contents of two or more arrays in a single array. In SQL we join tables based on a key, whereas in NumPy we join arrays by axes. We pass a sequence of arrays that we want to join to the concatenate() function, along with the axis.


2 Answers

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]
like image 99
Divakar Avatar answered Oct 12 '22 23:10

Divakar


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]
like image 42
morrna Avatar answered Oct 13 '22 00:10

morrna