Python Pandas - 将 DateTimeIndex 舍入为某个单位的倍数的频率
要将 DateTimeIndex 舍入为某个单位的倍数的频率,请使用 DateTimeIndex.round() 方法。为频率设置 freq 参数。
首先,导入所需的库 −
import pandas as pd
周期为 5 的 DatetimeIndex,频率为 H,即小时 −
datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='H')
显示 DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)
将 DateTimeIndex 舍入为 10 分钟频率,即某个单位的倍数。关于分钟频率,我们使用了“T−
print("\nPerforming round operation with multiples of a single unit frequency...\n", datetimeindex.round(freq='10T'))
示例
以下是代码 −
import pandas as pd # DatetimeIndex with period 5 and frequency as H i.e. hours # timezone is Australia/Adelaide datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='H') # display DateTimeIndex print("DateTimeIndex...\n", datetimeindex) # display DateTimeIndex frequency print("DateTimeIndex frequency...\n", datetimeindex.freq) # Round a DateTimeIndex with 10 minutes frequency i.e. multiples of a single unit # For minutes frequency, we have used 'T' print("\nPerforming round operation with multiples of a single unit frequency...\n", datetimeindex.round(freq='10T'))
输出
这将产生以下代码 −
DateTimeIndex... DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30', '2021-09-29 08:20:32.261811624+09:30', '2021-09-29 09:20:32.261811624+09:30', '2021-09-29 10:20:32.261811624+09:30', '2021-09-29 11:20:32.261811624+09:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='H') DateTimeIndex frequency... <Hour> Performing round operation with multiples of a single unit frequency... DatetimeIndex(['2021-09-29 07:20:00+09:30', '2021-09-29 08:20:00+09:30', '2021-09-29 09:20:00+09:30', '2021-09-29 10:20:00+09:30', '2021-09-29 11:20:00+09:30'], dtype='datetime64[ns, Australia/Adelaide]', freq=None)
广告