简体   繁体   中英

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.

在使用Nonenp.newaxis扩展第二个数组的维度后,您可以将broadcasting发挥到np.newaxis ,就像这样 -

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

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]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM