Home > other >  How to strip a 3D numpy array saved in a .txt file when trying to reopen it?
How to strip a 3D numpy array saved in a .txt file when trying to reopen it?

Time:10-25

I saved a bunch of 3D arrays into .txt files and would like to reopen them, however, I am having a ard time stripping them of the extra stuff and turning it back into a nparray. It seems to not be in the format to use any of the easier np.loadtxt from numpy. Here is what I get when I try to read the file...

['[[ 4.5177e 01  1.5709e 01 -2.3376e 01]\n',' [ 3.9789e 01  1.2330e 01 -2.4630e 00]\n', ' [ 3.9578e 01  1.6107e 01 -3.1490e 00]\n', ' [ 3.9285e 01  1.6824e 01  6.2000e-01]\n', ' [ 4.2083e 01  1.4330e 01  1.4770e 00]\n', ' [ 4.4570e 01  1.5651e 01 -1.1370e 00]\n', ' [ 4.3732e 01  1.9300e 01 -2.8900e-01]]']

I would just like the output as It was saved into the text file, a np array as such:

[[ 45.564  15.567 -23.417]
 [ 42.768  14.182 -21.219]
 [ 43.864  13.353 -17.643]
 [ 41.808   8.895  -9.964]
 [ 31.923  11.816  -8.006]
 [ 31.045   8.709  -5.931]]

CodePudding user response:

Watch the format in which you store the array. Looks like you're actually saving a "view" of an array (a string) instead of the numerical data itself. Try this instead:

mport numpy as np                                                                                      
                                                                                                        
a = [[ 45.564,  15.567, -23.417],                                                                       
     [ 42.768,  14.182, -21.219],                                                                       
     [ 43.864,  13.353, -17.643],                                                                       
     [ 41.808,   8.895,  -9.964],                                                                       
     [ 31.923,  11.816,  -8.006],                                                                       
     [ 31.045,   8.709,  -5.931]]                                                                       
                                                                                                        
np.savetxt("a.txt", a)                                                                                  
                                                                                                        
loaded_a = np.loadtxt("a.txt")                                                                                 
                                                                                                        
print(loaded_a[0])   

Notice the commas throughout the array.

  • Related