Python Pandas – 如何在具有分钟频率的DateTimeIndex上执行下取整操作
要在分钟频率的DateTimeIndex上执行下取整操作,请使用以下方法 DateTimeIndex.floor() 。 对于分钟频率,请使用具有值 ‘T’ 的 freq 参数。
首先,导入所需的库−
import pandas as pd
创建具有时间段为7和频率为s(即秒)的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("\n使用分钟频率进行下取整操作...\n",
datetimeindex.floor(freq='T'))
示例
以下是代码−
import pandas as pd
# DatetimeIndex with period 7 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)
# getting the minute
res = datetimeindex.minute
# display only the minute
print("\nThe minute from DateTimeIndex...\n", res)
# Floor operation on DateTimeIndex date with minute frequency
# For minute frequency, we have used 'T'
print("\n使用分钟频率进行下取整操作...\n",
datetimeindex.floor(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')
使用分钟频率进行下取整操作...
DatetimeIndex(['2021-10-18 07:20:00+10:30', '2021-10-18 07:21:00+10:30',
'2021-10-18 07:21:00+10:30', '2021-10-18 07:22:00+10:30',
'2021-10-18 07:23:00+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)