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

Python Pandas – DateTimeIndex의 날짜가 윤년인지 확인하는 방법

Pandas에서 DateTimeIndex에 포함된 날짜가 윤년(leap year)에 해당하는지 확인하려면 DateTimeIndex.is_leap_year 속성을 사용하면 됩니다. 이 속성은 각 날짜의 연도가 윤년이면 True, 그렇지 않으면 False를 요소로 가지는 불리언(Boolean) 배열을 반환합니다.

1. 라이브러리 임포트

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

import pandas as pd

2. DatetimeIndex 생성

시작 시점을 '2021-12-30 02:30:50'으로 지정하고, 주기(periods)는 6, 빈도(freq)는 '3Y'(3년 단위), 시간대(timezone)는 'Australia/Adelaide'로 설정하여 DatetimeIndex를 생성합니다.

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

3. DateTimeIndex 출력 및 윤년 여부 확인

생성된 DateTimeIndex를 화면에 출력한 뒤, is_leap_year 속성으로 각 날짜가 윤년에 속하는지 확인합니다.

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

print("\nCheck whether the date in DateTimeIndex belongs to a leap year or not...\n",
datetimeindex.is_leap_year)

전체 예제 코드

다음은 위 과정을 모두 포함한 전체 코드입니다.

import pandas as pd

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

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

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

# 각 날짜가 윤년에 속하는지 여부 확인
print("\nCheck whether the date in DateTimeIndex belongs to a leap year or not...\n",
datetimeindex.is_leap_year)

실행 결과

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

DateTimeIndex...
DatetimeIndex(['2021-12-31 02:30:50+10:30', '2024-12-31 02:30:50+10:30',
'2027-12-31 02:30:50+10:30', '2030-12-31 02:30:50+10:30',
'2033-12-31 02:30:50+10:30', '2036-12-31 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='3A-DEC')
DateTimeIndex frequency...
<3 * YearEnds: month=12>

Check whether the date in DateTimeIndex belongs to a leap year or not...
[False True False False False True]

결과 해석

출력 결과를 보면 생성된 날짜는 2021년, 2024년, 2027년, 2030년, 2033년, 2036년입니다. 이 중 2024년과 2036년은 4로 나누어떨어지는 윤년이므로 True가 반환되었고, 나머지 연도는 평년이므로 False가 반환되었습니다. 이처럼 is_leap_year 속성을 활용하면 DateTimeIndex의 각 날짜에 대해 윤년 여부를 손쉽게 벡터화 연산으로 확인할 수 있습니다.