len
len

Reputation: 807

How to read part of a text file using numpy.loadtxt and convert to array

I have a text file, which has the following content:

type=0
alg=1
c=3 5 7 8 10 11 14 15 16 17 
arr=(0, -7.05154314637184143066e-02) (1, -1.80315405130386352539e-01) (2, -3.32004070281982421875e-01) (3, 5.91193616390228271484e-01) (4, -1.21851079165935516357e-01) (5, -2.71257162094116210938e-01) (6, 2.46545433998107910156e-01) (7, 8.54252055287361145020e-02) 

How can I read from this text file (e.g with the name 'file.txt') the array arr and convert it to an array with two columns? The output should be:

array([[ 0.        , -0.07051543],
       [ 1.        , -0.18031541],
       [ 2.        , -0.33200407],
       [ 3.        ,  0.59119362],
       [ 4.        , -0.12185108],
       [ 5.        , -0.27125716],
       [ 6.        ,  0.24654543],
       [ 7.        ,  0.08542521]])

If I would have this line:

0,-7.05154314637184143066e-02,1,-1.80315405130386352539e-01,2,-3.32004070281982421875e-01,3, 5.91193616390228271484e-01,4,-1.21851079165935516357e-01,5,-2.71257162094116210938e-01,6, 2.46545433998107910156e-01,7,8.54252055287361145020e-02 

I could use:

import numpy as np
arr=np.loadtxt('file.txt', delimiter=',')
arr.reshape(-1,2)

Upvotes: 1

Views: 908

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114310

Simple Python will get you to where you can use np.fromstring:

for line in open('file.txt'):
    if line.startswith('arr='):
        line = line[5:].rstrip().rstrip(')').replace(') (', ',')
        arr = np.fromstring(line, sep=',').reshape(-1, 2)
        break  # or return arr
else:
    raise ValueError('SOL!')

Upvotes: 1

Related Questions