Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Pandas – DateTimeIndex의 날짜가 연도의 첫날인지 확인하는 방법

DateTimeIndex에 포함된 날짜가 해당 연도의 첫 번째 날인지 확인하려면 DateTimeIndex.is_year_start 속성을 사용하면 됩니다. 이 속성은 인덱스의 각 날짜가 연도의 시작일(1월 1일)에 해당하는지 여부를 불리언(Boolean) 배열로 반환해 주므로, 시계열 데이터에서 연초 기준의 조건 필터링이나 그룹화 작업에 유용하게 활용할 수 있습니다.

먼저 필요한 라이브러리를 임포트합니다.

import pandas as pd

기간(period)은 6, 빈도(freq)는 'D' 즉 일(day) 단위로 DatetimeIndex를 생성합니다. 시간대는 호주 애들레이드(Australia/Adelaide)로 지정했습니다.

datetimeindex = pd.date_range('2021-12-30 02:30:50', periods=6, tz='Australia/Adelaide', freq='1D')

생성된 DateTimeIndex를 출력하여 확인합니다.

print("DateTimeIndex...\n", datetimeindex)

이제 DateTimeIndex의 각 날짜가 연도의 첫 번째 날인지 여부를 확인합니다.

print("\nCheck whether the date in DateTimeIndex is the first day of the year...\n", datetimeindex.is_year_start)

전체 예제 코드

다음은 위 과정을 정리한 전체 코드입니다.

import pandas as pd

# 기간 6, 빈도 'D'(일 단위)로 DatetimeIndex 생성
# 시간대는 Australia/Adelaide로 지정
datetimeindex = pd.date_range('2021-12-30 02:30:50', periods=6, tz='Australia/Adelaide', freq='1D')

# DateTimeIndex 출력
print("DateTimeIndex...\n", datetimeindex)

# DateTimeIndex의 빈도(freq) 출력
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# 각 날짜가 연도의 첫 번째 날인지 확인
print("\nCheck whether the date in DateTimeIndex is the first day of the year...\n", datetimeindex.is_year_start)

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

DateTimeIndex...
DatetimeIndex(['2021-12-30 02:30:50+10:30', '2021-12-31 02:30:50+10:30',
'2022-01-01 02:30:50+10:30', '2022-01-02 02:30:50+10:30',
'2022-01-03 02:30:50+10:30', '2022-01-04 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='D')
DateTimeIndex frequency...
<Day>

Check whether the date in DateTimeIndex is the first day of the year...
[False False True False False False]

실행 결과를 보면 2021년 12월 30일부터 하루 간격으로 6개의 날짜가 생성되었으며, 그중 2022-01-01만 연도의 첫 번째 날에 해당하므로 세 번째 요소만 True로 반환된 것을 확인할 수 있습니다. 참고로 이 속성은 빈도(freq) 정보가 있는 DatetimeIndex에서 정확하게 동작하며, 반대 개념인 연도의 마지막 날 여부는 is_year_end 속성으로 확인할 수 있습니다.