【问题标题】:How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?如何从对象为 datetime.time 类型的 Pandas DataFrame.Index 中添加/减去时间(小时、分钟等)?
【发布时间】:2015-05-11 07:44:42
【问题描述】:

我有一个索引只是 datetime.time 的 DataFrame,并且 DataFrame.Index 和 datetime.time 中没有方法可以改变时间。 datetime.time 已替换,但仅适用于系列的个别项目?

下面是使用的索引示例:

In[526]:  dfa.index[:5]
Out[526]: Index([21:12:19, 21:12:20, 21:12:21, 21:12:21, 21:12:22], dtype='object')

In[527]:  type(dfa.index[0])
Out[527]: datetime.time

【问题讨论】:

  • type(df.index) 的输出是什么?
  • @MostafaMahmoud pandas.core.index.Index 但如果我输入(df.index[0]) 那就是 datetime.time。
  • @DreamAwake 使用pandas.Timestamp() 将当前索引转换为时间戳索引,然后对它进行任何操作。

标签: python datetime time pandas


【解决方案1】:

这个对我有用:

>> print(df)
                          TotalVolume  Symbol
2016-04-15 09:00:00       108400       2802.T
2016-04-15 09:05:00       50300        2802.T

>> print(df.set_index(pd.to_datetime(df.index.values) - datetime(2016, 4, 15)))

             TotalVolume  Symbol
09:00:00     108400       2802.T
09:05:00     50300        2802.T

【讨论】:

    【解决方案2】:

    Philippe 解决方案但更清洁:

    我的减法数据是:'2018-09-22T11:05:00.000Z'

    import datetime
    import pandas as pd
    
    df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)
    

    【讨论】:

      【解决方案3】:

      Liam 的链接看起来很棒,但也请查看 pandas.Timedelta - 看起来它与 NumPy 和 Python 的时间增量很好地配合。

      https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

      pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)
      

      【讨论】:

      • 使用 df.index + pd.Timedelta(hours=12) 给我错误“TypeError: +: 'numpy.ndarray' 和 'Timedelta' 的不支持的操作数类型”。索引本身是 pandas.core.index.Index 但每个值都是 datetime.time 以某种方式干扰 tshift() 方法以及 Timedelta 添加。
      • 查看 Mostafa 对您的原始问题的评论。转换为Timestamps
      • @MostafaMahmoud 你们真的能够获取一系列或索引 datetime.time 值并直接使用 pandas.Timestamp() 甚至使用 .to_timestamp() 方法进行转换吗?这些只会对我抛出错误。我正在考虑将 datetime.time 加入一个日期并直接形成一个 DatetimeIndex 但这不是最佳的,因为我的数据集只记录时间。
      • 请发布您正在使用的索引的示例。
      • df_series.index = (df_series.index + pd.Timedelta(days=1))
      猜你喜欢
      • 2017-07-24
      • 2019-06-07
      • 2018-03-06
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多