Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read flat list into multidimensional array/matrix in python

I have a list of numbers that represent the flattened output of a matrix or array produced by another program, I know the dimensions of the original array and want to read the numbers back into either a list of lists or a NumPy matrix. There could be more than 2 dimensions in the original array.

e.g.

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

Would produce:

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

Cheers in advance

like image 972
Chris Avatar asked Sep 03 '10 13:09

Chris


2 Answers

For those one liners out there:

>>> 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]])
like image 91
B.Mr.W. Avatar answered Nov 09 '22 03:11

B.Mr.W.


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 attribute of data if you want to avoid copying it in memory:

>>> data.shape = shape
like image 35
Katriel Avatar answered Nov 09 '22 05:11

Katriel