2

I have a very basic question. I think this can be done elegantly in a single line with numpy, but I don't know how. Let's say I have a 2D numpy array with shape (Nx,Ny), and I want to add a third dimension with shape Nz. For every fixed index_x,index_y I want to repeat the value of the array for all indices across the new z axis.

I can easily do this with basic instructions like

# array_1 has shape (Nx,Ny)
array_2 = np.zeros((Nx,Ny,Nz))

for idx_x in range(Nx):
    for idx_y in range(Ny):
        array_2[idx_x,idx_y,:] = array_1[idx_x,idx_y]

but I was wondering what is the exact numpy function to do this in a single line

2
  • reshape, expend_dims or the [:,:,None] idiom can be used to add a dimension. np.repeat (or np.tile) can repeat the values. Commented Apr 29, 2023 at 16:04
  • 1
    Try np.repeat(array_1[:, :, None], Nz, axis=2). Commented Apr 29, 2023 at 16:06

2 Answers 2

0

the logic depend, every plane is the same or is linear?

Must be a cube or something else?

comes from a rectangular shape or squared?

Anyway, use Array.reshape

This is a little example

Array2 = Array1.reshape(len(Array1), len(Array1[0]), <someValue>)

Another source

Sign up to request clarification or add additional context in comments.

2 Comments

This isn't syntactically correct - mismatch in number of ( and ).
hey thank you this was a little misslook
0

You have two options:

As mentioned in the comments, you can add another dimension to the array and repeat along that:

np.repeat(array_1[:, :, None], Nz, axis=2)

A better option is to use np.tile. You don't need to manually add a dimension and it can easily be extended to other cases when you want to repeat along one of the existing dimensions:

np.tile(array_1, (1, 1, Nz))

Basically, you specify how many times you want to repeat the array along each axis.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.