0

I have a 4D array: array = np.random.rand(3432,1,30,512)

I also have 5 sets of 2D arrays with shape (30,512)

I want to insert these into the 4D structure along axis 1 so that my final shape is (3432,6,30,512) (5 new arrays + the original 1). I need to iteratively insert this set for each of the 3432 elements

Whats the most effective way to do this?

I've tried reshaping the 2D to 4D and then inserting along axis 1. I'm expecting axis 1 to never exceed a size of 6, but the 2D arrays just keep getting added, rather than a set for each of the 3432 elements. I think my problem lies in not fully understanding the obj param for the insert method:

all_data = np.reshape(all_data, (-1, 1, 30, 512))

for i in range(all_data.shape[0]):
    num_band = 1
    for band in range(5):            
        temp_trial = np.zeros((30, 512))  # Just an example. values arent actually 0
        temp_trial = np.reshape(temp_trial, (1,1,30,512))
        all_data = np.insert(all_data, num_band, temp_trial, 1)

        num_band += 1
1
  • insert isn't meant for iterative work. Make sure you understand the docs examples first. Commented Dec 5, 2016 at 2:15

1 Answer 1

1

Create an array with the final shape first and insert the elements later:

final = np.zeros((3432,6,30,512))

for i in range(3432):  # note, this will take a while
    for j in range(6):
        final[i, j, :, :] = # insert your array here (np.ones((30, 512)))

or if you actually want to broadcast this over the zeroth axis, assuming each of the 3432 should be the same for each "band":

for i in range(6):
    final[:, i, :, :] = # insert your array here (np.ones((30, 512)))

As long as you don't do many loops there is no need to vectorize it

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

1 Comment

insert has to do this kind of allocate and copy anyways, so setting up the full size final at the start makes a lot of sense.

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.