Reading Data in Columns Python 2.7.3
Solution 1
If you're going to be plotting it with matplotlib, probably the simplest thing to do is to use numpy.loadtxt
[docs], because you'll have numpy installed anyway:
>>> import numpy
>>> d = numpy.loadtxt("mdat.txt", skiprows=2)
>>> d
array([[ 0. , 0.021],
[ 0.1 , 0.021],
[ 0.2 , 0.021],
[ 0.3 , 0.021],
[ 0.4 , 0.021],
[ 0.5 , 0.021],
[ 0.6 , 0.021]])
Note that I had to add skiprows=2
here to skip the header. Then the times are d[:,0]
and the charges d[:,1]
, or you could get them explicitly with loadtxt
:
>>> times, charges = numpy.loadtxt("mdat.txt", skiprows=2, unpack=True)
>>> times
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
>>> charges
array([ 0.021, 0.021, 0.021, 0.021, 0.021, 0.021, 0.021])
Solution 2
with open('data2.txt') as f:
f=[x.strip() for x in f if x.strip()]
data=[tuple(map(float,x.split())) for x in f[2:]]
charges=[x[1] for x in data]
times=[x[0] for x in data]
print('times',times)
print('charges',charges)
now charges and times contain:
times [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
charges [0.021, 0.021, 0.021, 0.021, 0.021, 0.021, 0.021]
Admin
Updated on December 14, 2020Comments
-
Admin over 3 years
I have a data file, which I need to read. I know to read files in Python you have to do something like:
file = open(fileLocaion, 'r+')
But I do not know who to do special reads. The data I have is in columns. So
x
values in one column andy
values in another with headers at the top. The data (my text filea.txt
) looks likeCharge (1x), Ch A, Run #1 Time ( s ) Charge (1x) ( µC ) 0.0000 0.021 0.1000 0.021 0.2000 0.021 0.3000 0.021 0.4000 0.021 0.5000 0.021 0.6000 0.021
So the first time value is
0.0000
and the first charge value is0.021
. I want to be able to take this into Python and usematplotlib
to plot it. But I am having trouble figuring out how to read this data.