Reading a flat list into a multidimensional array / matrix in python

I have a list of numbers that represent the smoothed output of a matrix or array created by another program, I know the size of the original array and I want to read the numbers back into the list of lists or the NumPy matrix. There may be more than two dimensions in the original array.

eg.

data = [0, 2, 7, 6, 3, 1, 4, 5] shape = (2,4) print some_func(data, shape) 

Will produce:

[[0,2,7,6], [3,1,4,5]]

Greetings in advance

+6
python numpy multidimensional-array
source share
3 answers

Use numpy.reshape :

 >>> import numpy as np >>> data = np.array( [0, 2, 7, 6, 3, 1, 4, 5] ) >>> shape = ( 2, 4 ) >>> data.reshape( shape ) array([[0, 2, 7, 6], [3, 1, 4, 5]]) 

You can also assign directly to the shape data attribute if you want to avoid copying it in memory:

 >>> data.shape = shape 
+16
source share

If you don't want to use numpy, there is a simple oneliner for the 2d case:

 group = lambda flat, size: [flat[i:i+size] for i in range(0,len(flat), size)] 

And it can be generalized to multidimensionality by adding recursion:

 import operator def shape(flat, dims): subdims = dims[1:] subsize = reduce(operator.mul, subdims, 1) if dims[0]*subsize!=len(flat): raise ValueError("Size does not match or invalid") if not subdims: return flat return [shape(flat[i:i+subsize], subdims) for i in range(0,len(flat), subsize)] 
+3
source share

For those one liner:

 >>> data = [0, 2, 7, 6, 3, 1, 4, 5] >>> col = 4 # just grab the number of columns here >>> [data[i:i+col] for i in range(0, len(data), col)] [[0, 2, 7, 6],[3, 1, 4, 5]] >>> # for pretty print, use either np.array or np.asmatrix >>> np.array([data[i:i+col] for i in range(0, len(data), col)]) array([[0, 2, 7, 6], [3, 1, 4, 5]]) 
0
source share

All Articles