Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape arbitrary length vector into square matrix with padding in numpy

Tags:

python

numpy

I have an arbitrary length vector, and I want to reshape it into a square matrix, something like:

np.arange(6).reshape((3, 3))

[1,2,x]   [1,2,3]    
[3,4,x]   [4,5,6]
[5,6,x]   [x,x,x] 

The x can be horizontally and/or vertically placed.

Obviously reshape function will only allow parameter like (3,2) in the above example. Is there a way to produce effect of squared shaped matrix.Thanks.

like image 750
motiur Avatar asked Dec 16 '16 02:12

motiur


People also ask

Is there reshape method in NumPy?

The numpy. reshape() function allows us to reshape an array in Python. Reshaping basically means, changing the shape of an array. And the shape of an array is determined by the number of elements in each dimension.

Why do we do reshape (- 1 1?

If you have an array of shape (2,4) then reshaping it with (-1, 1), then the array will get reshaped in such a way that the resulting array has only 1 column and this is only possible by having 8 rows, hence, (8,1).

How do you square a matrix in Python NumPy?

Python numpy. square() function returns a new array with the element value as the square of the source array elements. The source array remains unchanged.


1 Answers

You'll have to pad the array, either before or after reshape.

For example, using the resize method to add the needed 0s:

In [409]: x=np.arange(6)
In [410]: x.resize(3*3)
In [411]: x.shape
Out[411]: (9,)
In [412]: x.reshape(3,3)
Out[412]: 
array([[0, 1, 2],
       [3, 4, 5],
       [0, 0, 0]])

The np.resize replicates values. np.pad is also handy for adding 0s, though it might overkill.

With np.arange(6) we can pad before or after reshape. With np.arange(5) we have to stick with before, because the padding will be irregular.

In [409]: x=np.arange(6)
In [410]: x.resize(3*3)
In [411]: x.shape
Out[411]: (9,)
In [412]: x.reshape(3,3)
Out[412]: 
array([[0, 1, 2],
       [3, 4, 5],
       [0, 0, 0]])

In any case there isn't one function that does all of this in one call - at least not that I know of. This isn't a common enough operation.

like image 146
hpaulj Avatar answered Nov 15 '22 20:11

hpaulj