要将 DateTimeIndex 中的时间戳捕捉到最近的出现频率,请使用该方法。使用freq参数设置频率。DateTimeIndex.snap()
首先,导入所需的库 -
import pandas as pd
创建一个周期为 6 且频率为 D 的 DatetimeIndex -
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')
显示日期时间索引 -
print("DateTimeIndex...\n", datetimeindex)
将时间戳捕捉到最近发生的事件,即这里的月末 -
print("\nSnap time stamps to nearest occurring frequency...\n", datetimeindex.snap(freq='M'))
以下是代码 -
import pandas as pd # DatetimeIndex with period 6 and frequency as D i.e. day # The timezone is Australia/Adelaide datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D') # display DateTimeIndex print("DateTimeIndex...\n", datetimeindex) # display DateTimeIndex frequency print("\nDateTimeIndex frequency...\n", datetimeindex.freq) # Snap time stamps to nearest occurring i.e. Month end here print("\nSnap time stamps to nearest occurring frequency...\n", datetimeindex.snap(freq='M'))输出结果
这将产生以下代码 -
DateTimeIndex... DatetimeIndex(['2021-10-20 02:30:50+10:30', '2021-10-21 02:30:50+10:30', '2021-10-22 02:30:50+10:30', '2021-10-23 02:30:50+10:30', '2021-10-24 02:30:50+10:30', '2021-10-25 02:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='D') DateTimeIndex frequency... <Day> Snap time stamps to nearest occurring frequency... DatetimeIndex(['2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq=None)