PeriodIndex 객체에서 각 기간(period)의 월 번호를 확인하려면 PeriodIndex.month 속성을 사용하면 됩니다. 이 속성은 인덱스에 포함된 모든 기간의 월 값을 정수 형태로 반환합니다.
PeriodIndex란?
PeriodIndex는 시간상 규칙적인 기간을 나타내는 서수(ordinal) 값을 담고 있는 불변(immutable) 배열입니다. 날짜·시간 데이터를 분, 시간, 일 같은 일정한 주기 단위로 다룰 때 유용하게 활용됩니다.
라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
PeriodIndex 객체 생성
"freq" 매개변수를 사용해 빈도를 분(Minute) 단위로 설정한 PeriodIndex 객체를 생성합니다.
periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'], freq="T")
PeriodIndex 빈도 확인
생성된 PeriodIndex 객체의 빈도(freq) 정보를 출력해 확인할 수 있습니다.
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
월 번호 출력하기
PeriodIndex 객체에서 월 번호를 출력합니다. 월 번호는 1월=1, 2월=2 ... 12월=12 형태로 표시됩니다.
print("\nThe month number from the PeriodIndex object...\n", periodIndex.month)
전체 예제 코드
다음은 지금까지 설명한 내용을 정리한 전체 코드입니다.
import pandas as pd
# PeriodIndex 객체 생성
# PeriodIndex는 규칙적인 시간 기간을 나타내는 서수 값을 담는 불변 ndarray입니다.
# "freq" 매개변수로 빈도를 설정했습니다.
periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'], freq="T")
# PeriodIndex 객체 출력
print("PeriodIndex...\n", periodIndex)
# PeriodIndex 빈도 출력
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
# 문자열 형태의 PeriodIndex 빈도 출력
print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr)
# PeriodIndex 객체에서 월 번호 출력
# 월 번호는 1월=1, 2월=2 ... 12월=12로 표시됩니다.
print("\nThe month number from the PeriodIndex object...\n", periodIndex.month)
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
PeriodIndex... PeriodIndex(['2021-09-25 07:30', '2019-10-30 04:15', '2021-07-15 02:55', '2022-06-25 09:40'], dtype='period[T]') PeriodIndex frequency object... <Minute> PeriodIndex frequency object as a string... T The month number from the PeriodIndex object... Int64Index([9, 10, 7, 6], dtype='int64')
실행 결과에서 볼 수 있듯이, 각 날짜에 해당하는 월 번호인 9, 10, 7, 6이 순서대로 반환되었습니다. 이처럼 PeriodIndex.month 속성을 활용하면 시계열 데이터에서 월 단위 정보를 손쉽게 추출할 수 있습니다.