Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use np.resize to pad an array with np.nan

Tags:

python

numpy

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.

like image 241
piRSquared Avatar asked Dec 20 '16 23:12

piRSquared


1 Answers

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.

like image 89
wim Avatar answered Nov 19 '22 00:11

wim