1

There are those two numpy arrays:

a = np.array([
    [
        [1,2,3,0,0],
        [4,5,6,0,0],
        [7,8,9,0,0]
    ],
    [
        [1,3,5,0,0],
        [2,4,6,0,0],
        [1,1,1,0,0]
    ]
])

b = np.array([
    [
        [1,2],
        [2,3],
        [3,4]
    ],
    [
        [4,1],
        [5,2],
        [6,3]
    ]
])

with shapes:

"a" shape: (2, 3, 5), "b" shape: (2, 3, 2)

I want to replace the last two elements from array a with those from array b, e.g.

c = np.array([
    [
        [1,2,3,1,2],
        [4,5,6,2,3],
        [7,8,9,3,4]
    ],
    [
        [1,3,5,4,1],
        [2,4,6,5,2],
        [1,1,1,6,3]
    ]
])

However, np.hstack((a[:,:,:-2], b)) throws a Value Error:

all the input array dimensions except for the concatenation axis must match exactly

and in general doesn't look like it's the correct function to use. Append doesn't work either.

Is there a method in numpy that can do that or do I need to iterate over the arrays with a for loop and manipulate them manually?

2
  • 1
    a[:, :, -2:] = b Commented May 8, 2019 at 14:03
  • 1
    Or simply use the ellipsis notation, a[..., -2:] = b Commented May 8, 2019 at 14:37

2 Answers 2

3

You could use the direct indices like so:

a[:, :, 3:] = b
Sign up to request clarification or add additional context in comments.

Comments

1

Non-overwriting method:

  • a[:,:,-2:] fetches the zeros at the end; use a[:,:,:3].

  • According to the documentation, np.hstack(x) is equivalent to np.concatenate(x, axis=1). Since you want to join the matrices on their innermost rows, you should use axis=2.

Code:

>>> np.concatenate((a[:,:,:3], b), axis=2)
array([[[1, 2, 3, 1, 2],
        [4, 5, 6, 2, 3],
        [7, 8, 9, 3, 4]],

       [[1, 3, 5, 4, 1],
        [2, 4, 6, 5, 2],
        [1, 1, 1, 6, 3]]])

1 Comment

ah it's the second axis!! I was trying with 0 and 1 :facepalm:

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.