Say there's two 2D arrays, a and b
import numpy as np
a = np.random.rand(3, 4)
b = np.random.zeros(8, 8)
and b is always larger than a over both axes.
(Edit: b is initialized as an array of zeros, to reflect the fact that all elements not occupied by a will remain zero.)
Question. What's the fastest or most Pythonic way to "insert" a into b?
So far I've tried 2 things:
- Using
np.padto "turn"ainto an array of shape(8, 8) - Loop through every row in
aand place it in some the corresponding row inb
What I haven't tried is using a doubly-nested loop to iterate over every element of a, since I think that's not performance-friendly.
Motivation. Each array a is a tiny character, and I'd like to feed each character to a neural net that accepts flattened arrays of shape (8, 8), ie. arrays of shape (64,). (I think I can't simply flatten a to one dimension and pad it with zeros because then its two-dimensional structure gets warped, so, rather, I must first "reshape" it into (8, 8), right?) There's a few millions of characters.
bwith random values. So what do you need:apadded with the values fromb, or padded with zeroes? Is the padding at the right and bottom?b[?:?, ?:?] = a? That is slice a matching block ofbas place to putabshould actually benp.zeros. Also, the padding should ideally be centered, but the top left corner is also good.