读取长度可变的标题数据

时间:2018-10-29 11:45:17

标签: python-3.x pandas header formatting content-length

我想在python中读取一个包含长度可变的标头的文件,然后在数据帧/系列中提取标头后面的变量。
数据如下:

....................................................................
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
.....
..... 

所以我要提取的数据为:

    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

我可以使用

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'],)

但是我要跳过大约53行,因为我计算了应该跳过多少行。我有一堆这样的文件,有些文件的头中没有53行,所以我想知道什么是最好的处理方式,以及让Python在找到它们时始终只读取三列数据的标准?我想,如果我想让Python实际从遇到的地方读取数据

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

我该怎么办?那么使用另一个更好的标准呢?

1 个答案:

答案 0 :(得分:0)

您可以分割标题分隔符,如下所示:

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'],)