简体   繁体   English

在 Pandas datetimeindex 中将所有索引舍入到 30 分钟

[英]Round all index to 30 min in Pandas datetimeindex

I know about round, ceil, floor functions.我知道圆形,天花板,地板功能。

df.index.round("30min")

This rounds to the nearest 30 minute interval.这四舍五入到最接近的 30 分钟间隔。 What I want is that each is rounded to 30 minutes.我想要的是每个都四舍五入到 30 分钟。

In the case of.round 10:15 will be rounded to 10:30 and 10:45 to 11:00.在.round 的情况下,10:15 将四舍五入为 10:30,10:45 将四舍五入为 11:00。 I would want both rounded to 10:30.我希望两者都舍入到 10:30。

The datetime Index:日期时间索引:

DatetimeIndex(['2021-11-29 09:30:00', '2021-11-29 09:45:00',
               '2021-11-29 10:00:00', '2021-11-29 10:15:00',
               '2021-11-29 10:30:00', '2021-11-29 10:45:00',
               '2021-11-29 11:00:00', '2021-11-29 11:15:00',
               '2021-11-29 11:30:00', '2021-11-29 11:45:00',
               ...
               '2021-12-27 13:30:00', '2021-12-27 13:45:00',
               '2021-12-27 14:00:00', '2021-12-27 14:15:00',
               '2021-12-27 14:30:00', '2021-12-27 14:45:00',
               '2021-12-27 15:00:00', '2021-12-27 15:15:00',
               '2021-12-27 15:30:00', '2021-12-27 15:45:00'],
              dtype='datetime64[ns]', name='Datetime', length=520, freq=None)

Use DatetimeIndex.floor by hour and add 30 minutes:按小时使用DatetimeIndex.floor并加上 30 分钟:

df = pd.DataFrame(index=pd.DatetimeIndex(
               ['2021-11-29 09:30:00', '2021-11-29 09:45:00',
               '2021-11-29 10:00:00', '2021-11-29 10:15:00',
               '2021-11-29 10:30:00', '2021-11-29 10:45:00',
               '2021-11-29 11:00:00', '2021-11-29 11:15:00',
               '2021-11-29 11:30:00', '2021-11-29 11:45:00',
               '2021-12-27 13:30:00', '2021-12-27 13:45:00',
               '2021-12-27 14:00:00', '2021-12-27 14:15:00',
               '2021-12-27 14:30:00', '2021-12-27 14:45:00',
               '2021-12-27 15:00:00', '2021-12-27 15:15:00',
               '2021-12-27 15:30:00', '2021-12-27 15:45:00']))

print (df.index.floor("1H") + pd.Timedelta('30min'))

DatetimeIndex(['2021-11-29 09:30:00', '2021-11-29 09:30:00',
               '2021-11-29 10:30:00', '2021-11-29 10:30:00',
               '2021-11-29 10:30:00', '2021-11-29 10:30:00',
               '2021-11-29 11:30:00', '2021-11-29 11:30:00',
               '2021-11-29 11:30:00', '2021-11-29 11:30:00',
               '2021-12-27 13:30:00', '2021-12-27 13:30:00',
               '2021-12-27 14:30:00', '2021-12-27 14:30:00',
               '2021-12-27 14:30:00', '2021-12-27 14:30:00',
               '2021-12-27 15:30:00', '2021-12-27 15:30:00',
               '2021-12-27 15:30:00', '2021-12-27 15:30:00'],
              dtype='datetime64[ns]', freq=None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM