Python Pandas – 如何在DateTimeIndex上执行分钟级别的上取整操作
要在DateTimeIndex上执行分钟级别的上取整操作,请使用 DateTimeIndex.ceil() 方法。对于分钟级别,请使用值为 T 的 freq 参数。
首先,导入所需的库−
import pandas as pd
创建周期为5,频率为秒的DatetimeIndex−
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
显示DateTimeIndex−
print("DateTimeIndex...\n", datetimeindex)
对具有分钟频率的DateTimeIndex执行上取整操作。对于分钟频率,我们使用了’T −
print("\nPerforming ceil operation with minute frequency...\n",
datetimeindex.ceil(freq='T'))
示例
以下是代码−
import pandas as pd
# 创建周期为5,频率为秒的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频率
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# 获取分钟级别
res = datetimeindex.minute
# 显示仅分钟
print("\nThe minute from DateTimeIndex...\n", res)
# 对具有分钟频率的DateTimeIndex执行上取整操作
# 对于分钟频率,我们使用了'T'
print("\nPerforming ceil operation with minute frequency...\n",
datetimeindex.ceil(freq='T'))
输出
这将生成以下代码−
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>
The minute from DateTimeIndex...
Int64Index([20, 21, 21, 22, 23], dtype='int64')
Performing ceil operation with minute frequency...
DatetimeIndex(['2021-10-18 07:21:00+10:30', '2021-10-18 07:22:00+10:30',
'2021-10-18 07:22:00+10:30', '2021-10-18 07:23:00+10:30',
'2021-10-18 07:24:00+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)