pandas:read_csv仅排除某些行

时间:2015-01-02 11:17:37

标签: python csv pandas dataframe

我试图导入一个看起来像这样的csv文件

     Irrelevant row
"TIMESTAMP","RECORD","Site","Logger","Avg_70mSE_Avg","Avg_60mS_Avg",
"TS","RN","","","metres/second","metres/second",
"","","Smp","Smp","Avg","Avg",
"2010-05-18 12:30:00",0,"Sisters",5068,5.162,4.996
"2010-05-18 12:40:00",1,"Sisters",5068,5.683,5.571

第二行是标题,但第0行,第2行是无关紧要的。我的代码目前是:

parse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')

df = pd.read_csv('data.csv', header=1, index_col=['TIMESTAMP'],
                 parse_dates=['TIMESTAMP'], date_parser = parse)

问题在于,由于第2行和第3行没有正确的日期,我会收到错误(或者至少我认为这是错误)。

是否可以使用类似skiprows的内容排除这些行,但是对于不在文件开头的行?或者您还有其他建议吗?

1 个答案:

答案 0 :(得分:3)

您可以使用skiprows关键字忽略行:

pd.read_csv('data.csv', skiprows=[0, 2, 3], 
             index_col=['TIMESTAMP'], parse_dates=['TIMESTAMP'])

您的样本数据给出了:

                     RECORD     Site  Logger  Avg_70mSE_Avg  Avg_60mS_Avg
TIMESTAMP                                                                
2010-05-18 12:30:00       0  Sisters    5068          5.162         4.996
2010-05-18 12:40:00       1  Sisters    5068          5.683         5.571

第一个解析的行(1)成为标题,read_csv的默认解析器正确解析时间戳列。