The Oddler The Oddler - 3 months ago 19
Python Question

Python: numpy.matrix.resize moves elements

I have a numpy matrix:

[[ 0. 0.2 0. ]
[ 0. 0. 0.2]
[ 0. 0. 0. ]]


when I resize it
matrix.resize(4, 4)
, to have one extra row and column, it becomes:

[[ 0. 0.2 0. 0. ]
[ 0. 0.2 0. 0. ]
[ 0. 0. 0. 0. ]
[ 0. 0. 0. 0. ]]


The element on the second row is moved one to the left. It seems all elements are moved, and
0.
's are added at the bottom.

I would expect the matrix to become:

[[ 0. 0.2 0. 0. ]
[ 0. 0. 0.2 0. ]
[ 0. 0. 0. 0. ]
[ 0. 0. 0. 0. ]]


How can I fix this?

Note that I'm doing this for many different matrices, with many different values in it. So I'm looking for a simple solution that works for any size matrix, though the added column and row should contain all 0's.

Thanks!

Answer

You could use np.pad to pad the array:

import numpy as np

arr = np.array([[ 0.,   0.2,  0. ],
                [ 0.,   0.,   0.2],
                [ 0.,   0.,   0. ]])
np.pad(arr, pad_width=([0,1], [0,1]), mode='constant')

yields

array([[ 0. ,  0.2,  0. ,  0. ],
       [ 0. ,  0. ,  0.2,  0. ],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ,  0. ]])

pad_width=([0,1], [0,1]) tells np.pad to add

  • zero rows on top
  • one row on the bottom
  • zero columns on the left
  • one column on the right

mode='constant' uses 0 as the default constant pad value. There are lots of other modes, such as 'reflect', 'linear_ramp', 'edge', 'constant', 'minimum', 'wrap', 'symmetric', 'median', 'maximum', 'mean'.