Let
a = np.array([[1, 2], [3, 4]])
a
array([[1, 2],
[3, 4]])
Then use resize
b = np.resize(a, (3, 3))
b
array([[1, 2, 3],
[4, 1, 2],
[3, 4, 1]])
b
now has all of the information from a
if in a wonky order. Is there a way to leverage this to create what looks like a in the top left but now has one new column and one new row of np.nan?
c = np.empty(b.shape)
c.fill(np.nan)
c[:a.shape[0], :a.shape[1]] = a
c
array([[ 1., 2., nan],
[ 3., 4., nan],
[ nan, nan, nan]])
Obviously the above code accomplishes the same thing. I just can't help but think that resize
can be used in some way to accomplish this more efficiently.
Maybe look at pad
:
>>> np.pad(a, ((0,1),(0,1)), 'constant', constant_values=np.nan)
array([[ 1., 2., nan],
[ 3., 4., nan],
[ nan, nan, nan]])
Note that nan
is actually a float, so take care if trying to do this with integer dtypes. You might prefer to use masked arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With