DateTimeIndex의 타임스탬프를 가장 가까운 발생 빈도로 스냅(snap)하려면 DateTimeIndex.snap() 메서드를 사용하면 됩니다. 이때 freq 매개변수를 통해 기준이 될 주기를 지정할 수 있습니다.
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
기간(periods)이 6이고 빈도(freq)가 'D', 즉 일(day) 단위인 DatetimeIndex를 생성합니다. 시간대(timezone)는 호주 애들레이드로 설정했습니다.
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')생성된 DateTimeIndex를 출력해 확인해 보겠습니다.
print("DateTimeIndex...\n", datetimeindex)이제 타임스탬프를 가장 가까운 발생 빈도, 즉 여기서는 월말(Month end)로 스냅합니다.
print("\nSnap time stamps to nearest occurring frequency...\n", datetimeindex.snap(freq='M'))전체 예제 코드
지금까지 설명한 내용을 하나로 정리한 전체 코드는 다음과 같습니다.
import pandas as pd
# 기간 6, 빈도 D(일 단위)인 DatetimeIndex 생성
# 시간대는 Australia/Adelaide로 설정
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')
# DateTimeIndex 출력
print("DateTimeIndex...\n", datetimeindex)
# DateTimeIndex의 빈도 출력
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)
# 타임스탬프를 가장 가까운 발생 빈도(월말)로 스냅
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)
결과 해석
출력 결과를 보면 원래 DatetimeIndex는 2021년 10월 20일부터 25일까지 하루 간격으로 구성되어 있었습니다. 그러나 snap(freq='M')을 적용한 후에는 모든 타임스탬프가 해당 월의 마지막 날인 2021년 10월 31일로 이동한 것을 확인할 수 있습니다. 즉, snap() 메서드는 각 타임스탬프에서 지정한 주기에 해당하는 가장 가까운 시점을 찾아 자동으로 조정해 줍니다. 이 기능은 날짜 데이터를 특정 주기(월말, 분기 말 등)에 맞춰 정규화해야 할 때 유용하게 활용됩니다.