移动 pandas 日期时间索引

发布于 2025-01-17 05:39:43 字数 591 浏览 0 评论 0原文

我猜这是一个非常愚蠢的问题,但无论如何,这里是:

我有一个带有日期时间索引的数据框,如下所示:

DatetimeIndex(['1995-01-02', '1995-01-03', '1995-01-04', '1995-01-05',
               '1995-01-06', '1995-01-09', '1995-01-10', '1995-01-11',
                '1995-01-12', '1995-01-13'])

毫不奇怪,time字段是“00:00: 00":

bets.index.map(pd.datetime.time)

给出:

 Index([00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00,
       00:00:00, 00:00:00, 00:00:00])

我想将所有索引元素的时间字段设置为其他内容(例如中午)。最简单的方法是什么?

This is a really stupid question, I am guessing, but anyway, here goes:

I have a dataframe with a datetime index which looks like this:

DatetimeIndex(['1995-01-02', '1995-01-03', '1995-01-04', '1995-01-05',
               '1995-01-06', '1995-01-09', '1995-01-10', '1995-01-11',
                '1995-01-12', '1995-01-13'])

Not too surprisingly, the time field is "00:00:00":

bets.index.map(pd.datetime.time)

gives:

 Index([00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00,
       00:00:00, 00:00:00, 00:00:00])

I would like to set the time field to something else (e.g., noon), for all the index elements. What is the simplest way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花心好男孩 2025-01-24 05:39:43

IIUC,您可以使用 to_timedelta 并传入所需的小时数:

bets.index += pd.to_timedelta('12h')

输出:

DatetimeIndex(['1995-01-02 12:00:00', '1995-01-03 12:00:00',
               '1995-01-04 12:00:00', '1995-01-05 12:00:00',
               '1995-01-06 12:00:00', '1995-01-09 12:00:00',
               '1995-01-10 12:00:00', '1995-01-11 12:00:00',
               '1995-01-12 12:00:00', '1995-01-13 12:00:00'],
              dtype='datetime64[ns]', freq=None)

IIUC, you could use to_timedelta and pass in the required number of hours:

bets.index += pd.to_timedelta('12h')

Output:

DatetimeIndex(['1995-01-02 12:00:00', '1995-01-03 12:00:00',
               '1995-01-04 12:00:00', '1995-01-05 12:00:00',
               '1995-01-06 12:00:00', '1995-01-09 12:00:00',
               '1995-01-10 12:00:00', '1995-01-11 12:00:00',
               '1995-01-12 12:00:00', '1995-01-13 12:00:00'],
              dtype='datetime64[ns]', freq=None)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文