【问题标题】:Rounding error for datetimes when saving + reading an Excel file保存 + 读取 Excel 文件时日期时间的舍入错误
【发布时间】:2023-03-12 06:11:01
【问题描述】:

将带有日期时间的数据框保存到 Excel 文件并读回时,舍入错误会导致 datetime 相等测试错误:

import pandas as pd, datetime
df = pd.DataFrame({'A': [1, 2],     
                   'B': [datetime.datetime(2010,1,1,0,0,0), datetime.datetime(2013,9,10,11,13,55)]})
df.to_excel('test.xlsx')                # save to Excel file
df2 = pd.read_excel('test.xlsx')        # load to Excel file
print(df2)
S1 = {df2.loc[df['A'] == 1, 'B'].iat[0], datetime.datetime(2010,1,1,0,0,0)}
S2 = {df2.loc[df['A'] == 2, 'B'].iat[0], datetime.datetime(2013,9,10,11,13,55)}
print(S1)  # one single element, as expected
print(S2)  # two elements because of rounding errors

这里的集合S2 应该包含一个元素,因为其中的两个日期是相同的。

如何防止这个问题发生?


确实,这是从 Excel 文件中读取数据框的方式:

   Unnamed: 0  A                          B
0           0  1 2010-01-01 00:00:00.000000
1           1  2 2013-09-10 11:13:54.999999

注意:我有 pandas 版本 1.2.0、Python 3.7.6(64 位)、Windows。

链接到:https://datascience.stackexchange.com/questions/62977/pandas-datetime-error-when-reading-from-excel-file

【问题讨论】:

  • 未在我的系统上复制(Python 3.7、Pandas 1.1.4)。另外,我建议使用 Pandas 的日期时间而不是 Python 的日期时间。
  • @QuangHoang 我编辑并添加了我的问题中的版本。事实上,在我的真实代码中,我没有创建任何日期时间,它们都是从 Excel 文件中读取的(使用read_excel)。那么,你会如何使用 Pandas 的日期时间呢?
  • 既然你直接从excel文件中读取数据,那几乎肯定已经是Pandas datetime了。我不能再说什么,因为我的系统上没有复制。您可以尝试通过四舍五入来缓解问题:df['B'] = df['B'].dt.floor('S'),但不确定是否是您想要的。
  • @QuangHoang 我们是否可以通过类似read_excel(parse_dates=..., round_dates=...) 的操作自动舍入所有列的所有日期时间(无需一一指定)?
  • date_parser=lambda x: pd.to_datetime(x).dt.normalize() 也许?

标签: python excel pandas dataframe datetime


【解决方案1】:

这终于解决了:

df['B'] = df['B'].dt.round(freq='s')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    相关资源
    最近更新 更多