gpt4 book ai didi

python - Pandas to_datetime 格式错误没有错误

转载 作者:行者123 更新时间:2023-12-04 04:22:43 25 4
gpt4 key购买 nike

我读入了一个包含日期的 CSV 文件。有些日期可能格式错误,我想找到那些。通过以下方法,我会期望第二行是NaT。但是无论我设置 infer_datetime_format 还是 exact,pandas 似乎都会忽略指定的格式。

import pandas as pd
from io import StringIO

DATA = StringIO("""date
2019 10 07
2018 10
""")
df = pd.read_csv(DATA)

df['date'] = pd.to_datetime(df['date'], format="%Y %m %d", errors='coerce', exact=True)

结果

        date
0 2019-10-07
1 2018-10-01

pandas.to_datetime文档是指 strftime() and strptime() Behavior但是当我用普通的 Python 测试它时,它起作用了:

datetime.datetime.strptime('  2018 10', '%Y %m %d')

我得到期望值错误:

ValueError: time data '  2018 10' does not match format '%Y %m %d'

我错过了什么?

仅供引用:这个问题 pandas to_datetime not working似乎相关但不同,现在似乎已修复。它适用于我的 Pandas 版本 0.25.2。

最佳答案

这是一个已知错误,请参阅 github了解详情。

由于我们需要一个解决方案,所以我想到了以下解决方法。请注意,在我的问题中,我使用 read_csv 来保持可重现的代码片段小而简单。我们实际上使用了 read_fwf,这里是一些示例数据 (time.txt):

2019 10 07 + 14:45 15:00  # Foo
2019 10 07 + 18:00 18:30 # Bar
2019 10 09 + 13:00 13:45 # Wrong indentation

我觉得说明行号也是个好主意,所以我加了一点巫术:

class FileSanitizer(io.TextIOBase):
row = 0
date_range = None

def __init__(self, iterable, date_range):
self.iterable = iterable
self.date_range = date_range

def readline(self):
result = next(self.iterable)
self.row += 1
try:
datetime.datetime.strptime(result[self.date_range[0]:self.date_range[1]], "%Y %m %d")
except ValueError as excep:
raise ValueError(f'row: {self.row} => {str(excep)}') from ValueError
return result


filepath = 'time.txt'
colspecs = [[0, 10], [13, 18], [19, 25], [26, None]]
names = ['date', 'start', 'end', 'description']

with open(filepath, 'r') as file:
df = pd.read_fwf(FileSanitizer(file, colspecs[0]),
colspecs=colspecs,
names=names,
)

解决方案基于这个答案 How to skip blank lines with read_fwf in pandas? .请注意,这将read_csv 一起使用。

现在我得到了预期的以下错误:

ValueError: row: 3 => time data '  2019 10 ' does not match format '%Y %m %d'

如果有人有更复杂的答案,我很乐意学习。

关于python - Pandas to_datetime 格式错误没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58694383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com