熊猫提取注释行

时间:2016-09-27 12:10:29

标签: python pandas

我有一个数据文件,其中包含前几行注释,然后是实际数据。

#param1 : val1
#param2 : val2
#param3 : val3
12
2
1
33
12
0
12
...

我可以将数据读作pandas.read_csv(filename, comment='#',header=None)。但是我也希望单独阅读注释行以提取读取参数值。到目前为止,我只是跳过或删除注释行,但如何单独提取注释行?

2 个答案:

答案 0 :(得分:4)

在致read_csv的电话中你不能真的。如果您只是处理标题,则可以打开文件,提取注释行并处理它们,然后在单独的调用中读取数据。

from itertools import takewhile
with open(filename, 'r') as fobj:
    # takewhile returns an iterator over all the lines 
    # that start with the comment string
    headiter = takewhile(lambda s: s.startswith('#'), fobj)
    # you may want to process the headers differently, 
    # but here we just convert it to a list
    header = list(headiter)
df = pandas.read_csv(filename)

答案 1 :(得分:2)

也许你可以用正常的方式再次读取这个文件,读取每一行以获得你的参数。

def get_param( filename):
    para_dic = {}
    with  open(filename,'r') as cmt_file:    # open file
        for line in cmt_file:    # read each line
            if line[0] == '#':    # check the first character
                line = line[1:]    # remove first '#'
                para = line.split(':')     # seperate string by ':'
                if len(para) == 2:
                    para_dic[ para[0].strip()] = para[1].strip()
    return para_dic

此函数将返回包含参数的字典。

{'param3': 'val3', 'param2': 'val2', 'param1': 'val1'}