Haitham Fadila
Haitham Fadila

Reputation: 21

Adding column to higher dimension

let's assume that i have array called A

A = np.zeros((4, 3, 2))

array([[[0., 0.],
    [0., 0.],
    [0., 0.]],
   [[0., 0.],
    [0., 0.],
    [0., 0.]],
   [[0., 0.],
    [0., 0.],
    [0., 0.]],
   [[0., 0.],
    [0., 0.],
    [0., 0.]]])

and another array called B

B = np.arange(4)
array([0, 1, 2, 3])

and i want to do something like concatenation in the third dimension to got this result:

array([[[0., 0., 0.0],
    [0., 0., 0.0],
    [0., 0., 0.0]],
   [[0., 0., 1.0],
    [0., 0., 1.0],
    [0., 0., 1.0]],
   [[0., 0., 2.0],
    [0., 0., 2.0],
    [0., 0., 2.0]],
   [[0., 0., 3.0],
    [0., 0., 3.0],
    [0., 0., 3.0]]])

i tried serval ways to do that but i didn't succeed.
who i can do that in good way not loops?

Upvotes: 0

Views: 47

Answers (2)

yatu
yatu

Reputation: 88305

We could broadcast B to the corresponding shape and use advanced indexing here and assign B broadcasted across the corresponding axes:

np.concatenate([A, np.broadcast_to(B[:,None,None], A[...,-1:].shape)], -1)

print(A)

array([[[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 1.],
        [0., 0., 1.],
        [0., 0., 1.]],

       [[0., 0., 2.],
        [0., 0., 2.],
        [0., 0., 2.]],

       [[0., 0., 3.],
        [0., 0., 3.],
        [0., 0., 3.]]])

Upvotes: 0

Mark
Mark

Reputation: 92461

To add the extra dimension you can use np.append. You just have to get the shape correct. You can use np.repeat() to make the repeating elements:

A = np.zeros((4, 3, 2))
h, w, d = A.shape
B = np.repeat(np.arange(h), w).reshape([h, w, 1])

np.append(A, B, axis=2)

Output:

array([[[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 1.],
        [0., 0., 1.],
        [0., 0., 1.]],

       [[0., 0., 2.],
        [0., 0., 2.],
        [0., 0., 2.]],

       [[0., 0., 3.],
        [0., 0., 3.],
        [0., 0., 3.]]])

Upvotes: 1

Related Questions