Reading data in Python 2.7.3 columns

I have a data file that I need to read. I know in order to read files in Python you need to do something like:

file = open(fileLocaion, 'r+') 

But I do not know who to do special readings. The data I have is in columns. The x values ​​in one column and y values ​​in another with headers at the top. The data (my text file a.txt ) looks like

  Charge (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 is 0.021 . I want to be able to take this in Python and use matplotlib to build it. But it’s hard for me to understand how to read this data.

+4
source share
2 answers

If you are going to sketch it using matplotlib, perhaps the simplest is to use numpy.loadtxt [docs] , because you will 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 title. Then time d[:,0] and charges d[:,1] , or you can 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]) 
+8
source
 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) 

charges and time now 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] 
+4
source

All Articles