Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a 3d Array from File

Tags:

python

numpy

Lets say I have a file with the following values:

1 2
3 4

11 12
13 14

and I want to read them as a numpy 2x2x2 array. The standard command np.loadtxt('testfile') reads them in as lots of vectors ignoring the spaces (4x1x8). I suppose I could iterate over them and stack them together in the right way, but my actual data files are pretty large and would rather not have too many while loops if possible. Is there a nice way to do this within the numpy system?

Thanks for your help!

like image 256
Roger Hampton Avatar asked Jul 12 '13 15:07

Roger Hampton


1 Answers

Use reshape.

>>> import numpy
>>> a = numpy.loadtxt('testfile')
>>> a
array([[  1.,   2.],
       [  3.,   4.],
       [ 11.,  12.],
       [ 13.,  14.]])
>>> a.reshape((2, 2, 2))
array([[[  1.,   2.],
        [  3.,   4.]],

       [[ 11.,  12.],
        [ 13.,  14.]]])
like image 58
falsetru Avatar answered Oct 23 '22 23:10

falsetru