Pandas에서 DateTimeIndex.is_year_end 속성을 사용하면 DateTimeIndex에 포함된 각 날짜가 해당 연도의 마지막 날(12월 31일)인지 여부를 손쉽게 확인할 수 있습니다. 이 속성은 인덱스의 날짜 수만큼 True 또는 False 값으로 이루어진 불리언 배열을 반환하며, 특정 날짜가 연말이면 True, 그렇지 않으면 False를 나타냅니다.
1. 필요한 라이브러리 불러오기
먼저 pandas 라이브러리를 임포트합니다.
import pandas as pd
2. DatetimeIndex 생성하기
시작 시점을 '2021-12-25 02:30:50'으로 지정하고, 생성할 기간(periods)은 6개, 빈도(freq)는 '2D'(2일 간격), 시간대(tz)는 'Australia/Adelaide'로 설정하여 DatetimeIndex를 만듭니다.
datetimeindex = pd.date_range('2021-12-25 02:30:50', periods=6, tz='Australia/Adelaide', freq='2D')3. DateTimeIndex 출력하기
생성된 DateTimeIndex를 화면에 출력해 내용을 확인합니다.
print("DateTimeIndex...\n", datetimeindex)4. 연말(마지막 날) 여부 확인하기
is_year_end 속성을 사용하여 DateTimeIndex의 각 날짜가 해당 연도의 마지막 날인지 검사합니다.
print("\nCheck whether the date in DateTimeIndex is the last day of the year...\n", datetimeindex.is_year_end)전체 예제 코드
지금까지 설명한 내용을 하나로 합친 전체 코드는 다음과 같습니다.
import pandas as pd
# 기간 6개, 빈도 '2D'(2일 간격)로 DatetimeIndex 생성
# 시간대는 Australia/Adelaide로 설정
datetimeindex = pd.date_range('2021-12-25 02:30:50', periods=6, tz='Australia/Adelaide', freq='2D')
# DateTimeIndex 출력
print("DateTimeIndex...\n", datetimeindex)
# DateTimeIndex의 빈도(freq) 출력
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)
# 각 날짜가 해당 연도의 마지막 날인지 확인
print("\nCheck whether the date in DateTimeIndex is the last day of the year...\n",
datetimeindex.is_year_end)실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
DateTimeIndex... DatetimeIndex(['2021-12-25 02:30:50+10:30', '2021-12-27 02:30:50+10:30', '2021-12-29 02:30:50+10:30', '2021-12-31 02:30:50+10:30', '2022-01-02 02:30:50+10:30', '2022-01-04 02:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='2D') DateTimeIndex frequency... <2 * Days> Check whether the date in DateTimeIndex is the last day of the year... [False False False True False False]
결과 해석
생성된 DatetimeIndex에는 2021년 12월 25일부터 2일 간격으로 총 6개의 날짜가 포함되어 있습니다. 그중 네 번째 날짜인 2021년 12월 31일만 해당 연도의 마지막 날에 해당하므로, 결과 배열에서 네 번째 요소만 True이고 나머지는 모두 False로 표시됩니다. 참고로 2022년 1월 2일과 1월 4일은 새해의 날짜이지만 연말이 아니기 때문에 False로 판정됩니다.