The Oddler - 1 year ago 127

Python Question

I have a numpy matrix:

`[[ 0. 0.2 0. ]`

[ 0. 0. 0.2]

[ 0. 0. 0. ]]

when I resize it

`matrix.resize(4, 4)`

`[[ 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.`

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!

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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'.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**