简体   繁体   中英

Creating sub arrays from 1D array - Python

I have searched the Internet to try and find a solution and have tried to make my own but can't seem to figure it out.

I need to be able to take a 1D NumPy array and within that array, after every 1024 values they get turned into a 32x32 array and keep going until the initial array has been completely searched through and to avoid any errors simply append any zeros necessary to fill up the sub-arrays.

Any help or guidance would be appreciated!

You don't really need to do much. First pad the array to the nearest multiple of 1024:

arr = np.random.rand(1024 * 5 - 100)

pad = -arr.size % 1024
if pad:
    arr = np.concatenate((arr, np.zeros(pad, dtype=arr.dtype)))

Then reshape into an array of shape (N, 32, 32) :

imgs = arr.reshape(-1, 32, 32)

Now you have a stack of images. Indexing imgs or iterating over it will give you the individual (32, 32) images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM