Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading a text document with special formatting in to a numpy array

I have a text file with the following format:

(( X_value Y_value Z_value) ID)

I would like to read this into an array and I have been partly able to do with:
positions = np.genfromtxt(file, skip_header=N_header_lines, usecols=(1, 2, 3))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However I run into a problem when the X_value is negative this results in the following:

((-X_value Y_value Z_value) ID)

the problem being that Numpy now reads "((-X_value" as one column and does not separate the the string from the float.

I hope I was able to convey my problem clearly. Does someone know how to solve this problem.

>Solution :

Willian answer is great, however if you do not wish to load the text file and manipulate it before, you can use the following 1 liner –

arr = np.genfromtxt('blob.txt', usecols=(1,2,3),converters={i:lambda x: float(x.decode().strip('(').strip(')')) for i in [1,2,3]} )

Basically genfromtxt try to read the data into bytes and convert it to the right format, thus you can manipulate it using converters as you desire.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading