0

I have 2 numpy arrays:

array1 = np.load(r'C:\Users\x\array1.npy')
array2 = np.load(r'C:\Users\x\array2.npy')

I have to merge them in single array, so what I did was:

merg_arr = np.zeros((len(array1)+len(array2), 4, 100, 100), dtype=input_img.dtype)

for i in range(len(array1)+len(array2)):
    if i < len(array1):
        merg_arr[i] = array1[i]
    else:
        merge_arr[i] = array2[i-len(array1)]

It works in that way in case of 2 input arrays. Now I have 5 input arrays instead of two. But I am confused how to use the for loop in this case?

The shape of the 5 arrays and the expected output are:

array1: (7, 4 ,100, 100) 
array2: (14, 4 ,100, 100) 
array3: (5, 4 ,100, 100) 
array4: (8, 4 ,100, 100) 
array5: (66, 4 ,100, 100)
merg_arr: (100,4,100,100)
2

1 Answer 1

3

You could simply concatenate them along the first axis:

merg_arr = np.concatenate([array1, array2, array3, array4, array5], axis=0)

You can also do it with the for-loop:

arrays = (array1, array2, array3, array4, array5)
length_sum = sum(len(arr) for arr in arrays)
merge_arr = np.zeros((length_sum, 4,100,100), dtype=arrays[0].dtype)
start = 0
for arr in arrays:
    end = start + len(arr)
    merge_arr[start:end] = arr
    start = end

However concatenate is probably much easier.

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.