Home > OS >  (Numpy) How to stack 4 arrays into one?
(Numpy) How to stack 4 arrays into one?

Time:10-14

i have a list of 1000 numpy arrays (32x32) each, so

array.shape = (1000, 32, 32). How do i best go about stacking the entire list into a 64x64 array for example, so that the result is (250, 64, 64)? Hereby, the first 4 (32, 32) arrays are concatenated like so:

1   |   2
----------
3   |   4

This would mean that I end up with 250, 64x 64 arrays. Can anyone help out?

CodePudding user response:

You can also go over the colon notation here. This should have the same output as if you iterate over the arrays:

import numpy as np
large_array = np.zeros((1000, 32, 32))
output_array = np.zeros((250, 64, 64))

# Extract each block 1, 2, 3 and 4 and write to output array
# '::4' select only every fourth array
output_array[:, 0:32,  0:32] = large_array[0::4, ...]  # Blocks: '1'
output_array[:, 32:64, 0:32] = large_array[1::4, ...]  # Blocks: '2'
output_array[:, 0:32,  32:64] = large_array[2::4, ...] # Blocks: '3'
output_array[:, 32:64, 32:64] = large_array[3::4, ...] # Blocks: '4'

CodePudding user response:

This is a method that still uses a loop but does not create any new array beside the final one that gets filled iteratively

yourlist.shape == (1000,32,32)
new = np.empty((250, 64, 64))
s1 = slice(0, 32) # you can substitute it below with the standard :32 in the arrays below
s2 = slice(32,64)
for i in range(0, 1000, 4):
   a, b, c, d = yourlist[i:i 4]
   new[i // 4, s1, s1] = a
   new[i // 4, s1, s2] = b
   new[i // 4, s2, s1] = c
   new[i // 4, s2, s2] = d
  • Related