masoud
masoud

Reputation: 31

Loading numerical data from a text file in python

I have a text file which is

1.25e5  15

2.7e6   12

18.e5   14

I want to read the text as a 2d array and assign the first column as x and second as y.

Can anyone help me how can I do that. I did

f = open('energy.txt', 'r')
x = f.readlines()

but I don't know how to create the first column.

Upvotes: 1

Views: 207

Answers (1)

cs95
cs95

Reputation: 402493

Since you're okay with numpy, you can just use np.loadtxt:

In [270]: np.loadtxt('energy.txt')
Out[270]: 
array([[  1.25000000e+05,   1.50000000e+01],
       [  2.70000000e+06,   1.20000000e+01],
       [  1.80000000e+06,   1.40000000e+01]])

Alternatively, the python way to do this is:

In [277]: data = []

In [278]: with open('energy.txt') as f:
     ...:     for line in f:
     ...:         i, j = line.split()
     ...:         data.append([float(i), int(j)])
     ...:         

In [279]: data
Out[279]: [[125000.0, 15], [2700000.0, 12], [1800000.0, 14]]

With this approach, you store data as a list of lists, not a numpy array of floats. Also, you'll need to add a try-except in case you have any deviant lines in your file.

Upvotes: 1

Related Questions