lsterzinger
lsterzinger

Reputation: 717

expand and copy 1D numpy array to 3D

I have a 1D array that I need to be expanded to 3D, with the original array copied across axis=0.

Currently, I have a setup like this:

import numpy as np

x = np.array((1, 2, 3, 4, 5))
y = np.zeros((len(x), 5, 5))

for i in range(5):
  for j in range(5):
    y[:, i, j] = x

print(y)

[[[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]

 [[2. 2. 2. 2. 2.]
  [2. 2. 2. 2. 2.]
  [2. 2. 2. 2. 2.]
  [2. 2. 2. 2. 2.]
  [2. 2. 2. 2. 2.]]

 [[3. 3. 3. 3. 3.]
  [3. 3. 3. 3. 3.]
  [3. 3. 3. 3. 3.]
  [3. 3. 3. 3. 3.]
  [3. 3. 3. 3. 3.]]

 [[4. 4. 4. 4. 4.]
  [4. 4. 4. 4. 4.]
  [4. 4. 4. 4. 4.]
  [4. 4. 4. 4. 4.]
  [4. 4. 4. 4. 4.]]

 [[5. 5. 5. 5. 5.]
  [5. 5. 5. 5. 5.]
  [5. 5. 5. 5. 5.]
  [5. 5. 5. 5. 5.]
  [5. 5. 5. 5. 5.]]]

It strikes me that there should be an easier way to do this than with nested for loops, but anything that shows up with a cursory search shows how to cut up a long 1D array and make it 3D, but not copying the initial dimension into 2 more dimensions.

Upvotes: 3

Views: 3431

Answers (1)

javidcf
javidcf

Reputation: 59691

You have a couple of options. You can do it with np.tile like this:

y = np.tile(x[:, np.newaxis, np.newaxis], (1, 5, 5))

This will give you a new contiguous array with the contents you want. However, if you do not need to write into the resulting array, you can use np.broadcast_to to make a read-only view of the array with the new shape, saving you the memory of actually creating the bigger array:

y = np.broadcast_to(x[:, np.newaxis, np.newaxis], (5, 5, 5))

Note that, since this is a view, in this case changing a value in x would change the values in y.

Upvotes: 6

Related Questions