我正在尝试导入看起来像这样的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、3不相关。目前,我的代码是:
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
之类的方式排除这些行,但对于不在文件开头的行呢?或者您还有其他建议吗? 最佳答案
您可以使用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
的默认解析器正确解析timestamp列。关于python - Pandas :read_csv仅排除某些行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27741274/