5

I have a numpy array with dimensions 12 x 12 x 4. Now I'm trying to add an extra layer to this cube resulting in a 12 x 13 x 4 array. This 13th layer should contain the corresponding indices from the first axis, so for example addressing [7, 13, :] results in [7, 7, 7, 7].

Hard to explain but maybe someone has some advice on how to achieve this with numpy?

EDIT: I've found a solution, though it seems a little overcomplicated:

# Generate extra layer
layer = np.repeat(np.arange(0, 12)[:, np.newaxis], data.shape[2], axis=1)

# Get dimensions right...
layer = np.expand_dims(layer, axis=1)

# ... and finally append to data
result = np.append(data, layer, axis=1)

Still open for better suggestions.

1
  • Use concatenate. But be careful about dimensions. Commented Feb 6, 2018 at 15:47

1 Answer 1

2

You have the right idea. A slight simplification:

layer = np.repeat(np.arange(3)[:,None,None], data.shape[2], axis=2)
result = np.concatenate((data, layer), axis=1)
Sign up to request clarification or add additional context in comments.

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.