Carpet4
Carpet4

Reputation: 610

numpy 3d array and 1d array addition on first axis

i have a 1d np array "array1d" and a 3d np array "array3d", i want to sum them so the n'th value in "array1d" will be added to each of the elements of the n'th plane in array3d.

this can be done in the following loop

for i, value in enumerate(array1d):
    array3d[i] += value

question is, how can this be done in a single numpy line?

example arrays:

arr1d = np.array(range(3))
>>>array([0, 1, 2])

arr3d = np.array(range(27)).reshape(3, 3, 3)
>>>array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

wanted result:

array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 10, 11, 12],
        [13, 14, 15],
        [16, 17, 18]],

       [[20, 21, 22],
        [23, 24, 25],
        [26, 27, 28]]])

Upvotes: 0

Views: 177

Answers (1)

Graipher
Graipher

Reputation: 7186

Use Numpy's broadcasting features:

In [23]: arr1d[:, None, None] + arr3d
Out[23]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[10, 11, 12],
        [13, 14, 15],
        [16, 17, 18]],

       [[20, 21, 22],
        [23, 24, 25],
        [26, 27, 28]]])

This basically copies the content of arr1d across the other two dimensions (without actually copying, it just provides a view of the memory which looks like it). Instead of None, you can also use numpy.newaxis.

Alternatively, you can also use reshape:

In [32]: arr1d.reshape(3, 1, 1) + arr3d
Out[32]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[10, 11, 12],
        [13, 14, 15],
        [16, 17, 18]],

       [[20, 21, 22],
        [23, 24, 25],
        [26, 27, 28]]])

Upvotes: 1

Related Questions