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.

3
  • What must be the shape of output array? Commented Aug 29, 2015 at 7:29
  • For this example, it would need to retain the shape of the 3-D array, so 6,9,20 Commented Aug 29, 2015 at 7:31
  • 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. Commented Aug 29, 2015 at 7:31

3 Answers 3

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]
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.