PeriodIndex를 생성하려면 pandas.PeriodIndex() 메서드를 사용하고, 특정 월의 일수(날짜 수)를 가져오려면 PeriodIndex.daysinmonth 속성을 활용하면 됩니다.
필요한 라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
PeriodIndex 객체 생성하기
PeriodIndex는 시간상 규칙적인 기간(regular periods)을 나타내는 서수(ordinal) 값을 담고 있는 불변(immutable) ndarray입니다. 아래 예제에서는 freq 매개변수를 사용해 빈도를 'D'(일 단위)로 설정했습니다.
periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'], freq="D")
생성된 PeriodIndex 객체를 출력합니다.
print("PeriodIndex...\n", periodIndex)이어서 PeriodIndex 객체에서 특정 월의 일수를 출력합니다.
print("\nDays of the specific month from the PeriodIndex...\n", periodIndex.daysinmonth)전체 예제 코드
다음은 지금까지 설명한 내용을 모두 포함한 전체 코드입니다.
import pandas as pd
# PeriodIndex 객체 생성
# PeriodIndex는 규칙적인 시간 기간을 나타내는 서수 값을 담는 불변 ndarray입니다.
# "freq" 매개변수로 빈도를 설정합니다.
periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")
# PeriodIndex 객체 출력
print("PeriodIndex...\n", periodIndex)
# PeriodIndex 빈도 출력
print("\nPeriodIndex frequency...\n", periodIndex.freq)
# 월 번호 출력 (1 = 1월, 2 = 2월 ... 12 = 12월)
print("\nMonth number...\n", periodIndex.month)
# PeriodIndex 객체에서 특정 월의 일수 출력
print("\nDays of the specific month from the PeriodIndex...\n", periodIndex.daysinmonth)실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
PeriodIndex... PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'], dtype='period[D]') PeriodIndex frequency... <Day> Month number... Int64Index([7, 10, 11, 9, 3, 6], dtype='int64') Days of the specific month from the PeriodIndex... Int64Index([31, 31, 30, 30, 31, 30], dtype='int64')
출력 결과에서 볼 수 있듯이, daysinmonth 속성은 각 날짜가 속한 월의 총 일수를 반환합니다. 예를 들어 7월은 31일, 11월은 30일인 것처럼 실제 달력에 맞는 값이 자동으로 계산됩니다. 이 속성은 윤년 여부까지 고려하므로 2월의 경우에도 정확한 일수(28일 또는 29일)를 얻을 수 있습니다.