Python Pandas – 如何对指定频率的DateTimeIndex执行ceil操作
要在指定频率的DateTimeIndex上执行ceil操作,请使用 DateTimeIndex.ceil() 方法 。使用 freq 参数设置频率。
首先导入所需的库−
import pandas as pd
使用周期为5,频率为秒(S)的DatetimeIndex创建。时区为Australia/Adelaide −
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
显示DateTimeIndex−
print("DateTimeIndex...\n", datetimeindex)
针对指定频率的DateTimeIndex日期执行Ceil操作−
print("\n执行向上取整操作...\n", datetimeindex.ceil(freq='us'))
更多Pandas文章,请阅读:Pandas教程
示例
以下是代码−
import pandas as pd
# DatetimeIndex with period 5 and frequency as S i.e. seconds
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# Ceil operation on DateTimeIndex date with frequency
print("\n执行向上取整操作...\n", datetimeindex.ceil(freq='us'))
输出结果
这将产生以下代码 −
DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30',
'2021-10-18 07:21:12.261811624+10:30',
'2021-10-18 07:21:52.261811624+10:30',
'2021-10-18 07:22:32.261811624+10:30',
'2021-10-18 07:23:12.261811624+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='40S')
DateTimeIndex frequency...
<40 * 秒(Seconds)>
执行向上取整操作...
DatetimeIndex(['2021-10-18 07:20:32.261812+10:30',
'2021-10-18 07:21:12.261812+10:30',
'2021-10-18 07:21:52.261812+10:30',
'2021-10-18 07:22:32.261812+10:30',
'2021-10-18 07:23:12.261812+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)