Pandas Value-Error: "time data 'nan' does not match format", when using "read_csv" with "date_parser" and "comment"

Pandas Value-Error: "time data 'nan' does not match format", when using "read_csv" with "date_parser" and "comment"

我正在使用:Python 3.7.2 & Pandas 0.24.2 我尝试读取以下数据 (data.txt)。以空格分隔,第一列应解析为日期时间对象:

       #00:00:00               col0       col1
       2019-03-28_08:58:00     1064      31965
       2019-03-28_09:08:00     1084      32565
       !2019-03-28_09:18:00    1104      33165
       2019-03-28_09:28:00     1124      33765

与 pandas read_csv 为:

import pandas as pd
import datetime 

def date_parser (s):
    return datetime.datetime.strptime(str(s),'%Y-%m-%d_%H:%M:%S')

df      = pd.read_csv(filepath_or_buffer='data.txt',
                      delim_whitespace = True,
                      index_col='#00:00:00',
                      parse_dates=True,
                      date_parser=date_parser,
                      comment='!',
                      )

应跳过所有以特殊字符(此处:!)开头的行。它可以是任何其他字符。但是对于注释行,我总是收到错误:

ValueError: time data 'nan' does not match format '%Y-%m-%d_%H:%M:%S'

感谢您的任何想法

您提供的示例代码对我来说工作正常。我使用与您相同的 Pandas 版本和 Python 3.7:

It's working...

我从您提供的输入文件中删除了多余的空格:

#00:00:00 col0 col1
2019-03-28_08:58:00 1064 31965
2019-03-28_09:08:00 1084 32565
!2019-03-28_09:18:00 1104 33165
2019-03-28_09:28:00 1124 33765

试试这个方法:

df.columns = ["date", "c1", "c2"]
df.head()

date    c1  c2
0   2019-03-28_08:58:00 1064    31965
1   2019-03-28_09:08:00 1084    32565
2   2019-03-28_09:18:00 1104    33165
3   2019-03-28_09:28:00 1124    33765

df.dtypes
date    object
c1       int64
c2       int64
dtype: object

df.date = pd.to_datetime(df.date, format='%Y-%m-%d_%H:%M:%S')

df.dtypes

date    datetime64[ns]
c1               int64
c2               int64
dtype: object

之后您还可以执行这些操作来提取年份、小时或日期,例如:df.date.dt.year df.date.dt.hour 或 df.date.dt.date