Read 3D array from file

Let's say I have a file with the following values:

1 2 3 4 11 12 13 14 

and I want to read them as an numx 2x2x2 array. The standard np.loadtxt('testfile') reads them as a set of vectors ignoring spaces (4x1x8). I suppose I could iterate over them and stack them correctly, but my actual data files are quite large and would rather not have too many loops if possible. Is there a good way to do this on a numpy system?

Thank you for your help!

+4
source share
1 answer

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.]]]) 
+6
source

Source: https://habr.com/ru/post/1491148/


All Articles