简体   繁体   中英

Numpy matrix from text file

I am writing a matrix into a text file and need to read the file in another python script. The second script needs to get the text back into a numpy array. I have been struggling to find out how to do this, any help would be greatly appreciated. Two examples of the array are given below:

[[ 0.  0. -0.]
 [ 0.  0.  0.]
 [ 0.  0. -0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

or

[[ 0.          0.         -0.03011621]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.         -0.06023241]
 [ 0.          0.         -0.01204648]]

To save to a text file, use np.savetxt

In [115]: x = np.zeros((10, 3))

In [116]: np.savetxt('/tmp/test.out', x)

To load, use np.loadtxt or np.genfromtxt :

In [117]: y = np.genfromtxt('/tmp/test.out')

In [120]: y.shape
Out[120]: (10, 3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM