简体   繁体   中英

converting an string matrix to numpy ndarray

considering a matrix like:

+0.00000E+00 +0.00000E+00\n +0.00000E+00 +0.00000E+00\n +0.00000E+00 +0.00000E+00

that is originally extracted from a text file, I want to convert it to a numpy ndarray of size 3 by 2 with pure int elements. I tried simple int function, pickle module and some other methods with no luck.

You can do this:

string = "+0.00000E+00 +0.00000E+00\n +0.00000E+00 +0.00000E+00\n +0.00000E+00 +0.00000E+00"
array_n = re.findall(r'\S+', string)
array_n = np.array(array_n)

array_out = array_n.reshape(3,2)

which gives:

array([['+0.00000E+00', '+0.00000E+00'],
       ['+0.00000E+00', '+0.00000E+00'],
       ['+0.00000E+00', '+0.00000E+00']], dtype='<U12')

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