Python Pandas - 将 DateTimeIndex 中的时间戳捕捉到最近发生的频率\n\n
若要将 DateTimeIndex 中的时间戳捕捉到最近发生的频率,请使用 DateTimeIndex.snap() 方法。使用 freq 参数设置频率。
首先,导入所需的库 −
import pandas as pd
使用周期 6 和频率为 D(即天)创建一个 DatetimeIndex −
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')
显示 DateTimeIndex −
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)
广告