0

I have a file containing the following strings:

 1    40.870     0.710  570  363
0.00000E+00
 2    40.960     0.870  575  367
0.00000E+00
 3    41.210     0.980  578  378
0.00000E+00

And I need to convert it in a matrix like that:

     40.870     0.710  0.000
     40.960     0.870  0.000
     41.210     0.980  0.000

Any help would be greatly appreciated

1
  • You can read line by line, split the line, store what you need and go on. Commented Dec 10, 2015 at 14:08

4 Answers 4

1
def rows(data):
    while True:             
        a = next(data).split()
        b = next(data).split()
        yield float(a[1]), float(a[2]), float(b[0])

list(rows(open("somefile.txt")))
[(40.87, 0.71, 0.0), (40.96, 0.87, 0.0), (41.21, 0.98, 0.0)]

numpy.array(list(rows(open("somefile.txt"))))
array([[ 40.87,   0.71,   0.  ],
       [ 40.96,   0.87,   0.  ],
       [ 41.21,   0.98,   0.  ]])

P.S. I've no clue what those fields 570 and 363 were that were ignored...

Sign up to request clarification or add additional context in comments.

Comments

1
import pandas as pd
take_cols = [1,2,5]
mat = pd.read_table(in_file,sep="\t",usecols=take_cols)

Comments

0

You could read your file with read_table from pandas package. Then subset it to use columns which you need, and then get values of that dataframes with values method which return numpy array:

import pandas as pd
df = pd.read_table(file, sep='\s+', header=False)

In [157]: df
Out[157]: 
   0      1     2    3    4  5
0  1  40.87  0.71  570  363  0
1  2  40.96  0.87  575  367  0
2  3  41.21  0.98  578  378  0


mat = df[[1,2,5]].values

In [160]: mat
Out[160]: 
array([[ 40.87,   0.71,   0.  ],
       [ 40.96,   0.87,   0.  ],
       [ 41.21,   0.98,   0.  ]])

Comments

0

thank you very much to all, I also finally found another solution:

c = 0
f = open(fich_interp_out, 'w')
for i in open(fich_interp, 'r'):
    if c<3:
        pass

    elif c%2 != 0:

        s = i[:-1]
    else:
        s += i
        f.write(s)

    c+=1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.