Simon
Simon

Reputation: 10158

numpy insert 2D array into 4D structure

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

Upvotes: 0

Views: 719

Answers (1)

MSeifert
MSeifert

Reputation: 152860

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

Upvotes: 1

Related Questions