Python Pandas – 如何在DateTimeIndex上执行毫秒级别的floor操作
若要在毫秒级频率的DateTimeIndex上执行floor操作,则使用 DateTimeIndex.floor() 方法。对于毫秒级频率,请使用值为 ‘us’ 的 freq 参数。
首先,导入所需的库−
import pandas as pd
带周期为7和频率为秒的DatetimeIndex,时区为Australia/Adelaide −
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
DateTimeIndex日期进行毫秒级floor操作。对于毫秒级频率,我们使用“us”−
print("\nPerforming floor operation with microseconds frequency...\n",
datetimeindex.floor(freq='us'))
更多Pandas文章,请阅读:Pandas教程
示例
以下是代码−
import pandas as pd
# 带周期为7和频率为秒的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)
# DateTimeIndex日期进行毫秒级floor操作。对于毫秒级频率,我们使用“us”
print("\nPerforming floor operation with microseconds frequency...\n",
datetimeindex.floor(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日期进行毫秒级floor操作。对于毫秒级频率,我们使用“us”
DatetimeIndex(['2021-10-18 07:20:32.261811+10:30',
'2021-10-18 07:21:12.261811+10:30',
'2021-10-18 07:21:52.261811+10:30',
'2021-10-18 07:22:32.261811+10:30',
'2021-10-18 07:23:12.261811+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)