2016-04-21 43 views
0

头我有一个文件看起来像获得注释的一个特定的行与蟒蛇熊猫

# Comment 1 
# Comment 2 
# A B C 
1 2 3 
4 5 6 
7 8 9 

如何使用Python大熊猫模块读取它,这样的评论的最后一行可以被解释为列标题?

我已经试过

pandas.read_table(file_path, header= 2 , comment='#') 

但注释行第一淘汰,因此标题行会 7 8 9

回答

2

您可以手动执行此操作:先读的评论,解析列名,然后调用read_table

import itertools 
import pandas as pd 

def read_data(path): 
    with open(path) as handle: 
     *_comments, names = itertools.takewhile(
      lambda line: line.startswith('#'), handle) 

     # This is not the most robust way, adjust for your needs :) 
     names = names[1:].split() 

    return pandas.read_table(path, header=0, names=names, sep=' ', comment='#') 
0
In [7]: pd.read_csv('test.csv',skiprows=2,sep='\s+',escapechar='#') 
Out[7]: 
    A B C 
0 1 2 3 
1 4 5 6 
2 7 8 9 

escapechar告诉#必须考虑为场终止。在这里它被用作一个干净的解决方法。这里需要sep='\s+',因为在文件(或本页)中有3和6之后的空格。