【问题标题】:Pandas datetime values messed up after saving df to excel and then reading back into a df将 df 保存到 excel 然后读回 df 后,Pandas 日期时间值搞砸了
【发布时间】:2021-06-22 10:32:14
【问题描述】:
jan_21=[datetime(2021,1,1) + timedelta(hours=i) for i in range(5)]


jan_21
    
[datetime.datetime(2021, 1, 1, 0, 0),
 datetime.datetime(2021, 1, 1, 1, 0),
 datetime.datetime(2021, 1, 1, 2, 0),
 datetime.datetime(2021, 1, 1, 3, 0),
 datetime.datetime(2021, 1, 1, 4, 0)]

prices = np.random.randint(1,100,size=(5,))

prices

[46 23 13 26 52]

df = pd.DataFrame({'datetime':jan_21, 'price':prices})

df

             datetime  price
0 2021-01-01 00:00:00     83
1 2021-01-01 01:00:00     60
2 2021-01-01 02:00:00     29
3 2021-01-01 03:00:00     97
4 2021-01-01 04:00:00     67

到目前为止一切顺利,这就是我期望数据框和日期时间值的显示方式。当我将数据框保存到 excel 文件然后将其读回数据框时,问题就出现了,日期时间值被弄乱了。

df.to_excel('price_data.xlsx', index=False)

new_df = pd.read_excel('price_data.xlsx')

new_df

                      datetime  price
0   2021-01-01 00:00:00.000000  83
1   2021-01-01 00:59:59.999999  60
2   2021-01-01 02:00:00.000001  29
3   2021-01-01 03:00:00.000000  97
4   2021-01-01 03:59:59.999999  67

我希望 df == new_df 评估为 True

【问题讨论】:

    标签: python python-3.x excel pandas dataframe


    【解决方案1】:

    在问题可能原因的背景下(请参阅 sophros 的回答),您可以做的 - 表面上 - 规避问题是在生成 excel 文件之前将df["datetime"] 的单元格转换为字符串,然后将在创建new_df 之后再次将字符串转换为日期时间:

    df["datetime"] = df["datetime"].dt.strftime("%m/%d/%Y, %H:%M:%S")
    df.to_excel('price_data.xlsx', index=False)
    
    new_df = pd.read_excel('price_data.xlsx')
    new_df["datetime"] = pd.to_datetime(new_df["datetime"], format="%m/%d/%Y, %H:%M:%S")
    

    【讨论】:

    • 是的,这正是我刚刚尝试过的,并且有效!
    • @PruthviAmin 很高兴它有效!不过,如果是这种情况,您应该接受答案。
    【解决方案2】:

    00:59:59.99999902:00:00.00000103:59:59.999999 的时间部分不同的原因很可能与 ExcelPythonpandas 中日期/时间类型的二进制表示略有不同有关.

    时间经常以浮点数形式存储,但不同之处在于第 0 次是什么时候(例如 1 AC 或 1970 年 - 如在 Linux 中;good explanation here)。因此,转换可能会丢失日期/时间的一些最不重要的部分,您对此无能为力,只能将其四舍五入或使用approximate comparisons as with any float

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2021-10-22
      • 2015-08-05
      • 1970-01-01
      • 2012-05-11
      • 2023-04-05
      • 1970-01-01
      • 2019-09-12
      • 2013-01-19
      相关资源
      最近更新 更多