0

I want to read in python a file which contains a varying length header and then extract in a dataframe/series the variables which are coming after the header.
The data looks like :

....................................................................
Data coverage and measurement duty cycle:
When the instrument duty cycle is not in measure mode (i.e. in-flight     
calibrations) the data is not given here (error flag = 2). 

The measurements have been found to exhibit a strong sensitivity to cabin 
pressure.
Consequently the instrument requires calibrated at each new cabin    
pressure/altitude.

Data taken at cabin pressures for which no calibration was performed is    
not given here (error flag = 2).
Measurement sensivity to large roll angles was also observed.
Data corresponding to roll angles greater than 10 degrees is not given    
here (error flag = 2)
......................................................................
High Std: TBD ppb
Target Std: TBD ppb
Zero Std: 0 ppb

Mole fraction error flag description :
0 : Valid data
2 : Missing data
31636 0.69 0
31637 0.66 0
31638 0.62 0
31639 0.64 0
31640 0.71 0
.....
..... 

So what I want is to extract the data as :

    Time    C2H6  Flag
0  31636  0.69 0   NaN
1  31637  0.66 0   NaN
2  31638  0.62 0   NaN
3  31639  0.64 0   NaN
4  31640  0.71 0   NaN
5  31641  0.79 0   NaN
6  31642  0.85 0   NaN
7  31643  0.81 0   NaN
8  31644  0.79 0   NaN
9  31645  0.85 0   NaN

I can do that with

infile="/nfs/potts.jasmin-north/scratch/earic/AEOG/data/mantildas_faam_20180911_r1_c118.na"
flightdata = pd.read_fwf(infile, skiprows=53, header=None, names=['Time', 'C2H6', 'Flag'],)

but I m skipping approximately 53 rows because I counted how much I should skip. I have a bunch of these files and some don't have exactly 53 rows in the header so I was wondering what would be the best way to deal with this and a criteria to have Python always only read the three columns of data when finds them? I thought if I'd want let's say Python to actually read the data from where encounters

Mole fraction error flag description :
0 : Valid data
2 : Missing data

what should I do ? What about another criteria to use which would work better ?

The Dude
  • 61
  • 8

1 Answers1

0

You can split on the header delimiter, like so:

with open(filename, 'r') as f:
    myfile = f.read()
infile = myfile.split('Mole fraction error flag description :')[-1]
# skip lines with missing data
infile = infile.split('\n')
# likely a better indicator of a line with incorrect format, you know the data better
infile = '\n'.join([line for line in infile if ' : ' not in line])
# create dataframe
flightdata = pd.read_fwf(infile, header=None, names=['Time', 'C2H6', 'Flag'],)
Ethan Koch
  • 267
  • 1
  • 6