8

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.

user6903745
  • 5,267
  • 3
  • 19
  • 38
piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • Related: http://stackoverflow.com/q/12668027/674039 – wim Dec 20 '16 at 23:57
  • That `wonky order` is just repeated copies of the data (as flattened). `c.resize` pads with 0s, but again in the flattened order. Neither form of `resize` gets used much. – hpaulj Dec 21 '16 at 00:38
  • 1
    Your last code is not inefficient. It may be a bit wordy, but it is more efficient than `pad`, which has to be much more general purposed. Look at the code for `np.resize`, `np.full` and `np.pad` - those are all written in Python. – hpaulj Dec 21 '16 at 00:53

1 Answers1

11

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.

wim
  • 338,267
  • 99
  • 616
  • 750