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

Python Pandas – PeriodIndex 생성 및 요일(dayofweek) 구하기

PeriodIndex란 무엇인가?

Pandas에서 PeriodIndex는 시간상의 규칙적인 기간(period)을 나타내는 서수(ordinal) 값을 저장하는 불변(immutable) ndarray입니다. PeriodIndex를 생성하려면 pandas.PeriodIndex() 메서드를 사용하고, 요일을 구하려면 PeriodIndex.dayofweek 속성을 활용하면 됩니다.

라이브러리 임포트하기

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

import pandas as pd

PeriodIndex 객체 생성하기

날짜 문자열 리스트를 전달하여 PeriodIndex 객체를 생성합니다. 이때 freq 매개변수를 사용해 빈도(frequency)를 지정할 수 있습니다. 아래 예제에서는 일 단위 빈도인 "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 출력하기

생성된 PeriodIndex 객체를 화면에 표시합니다.

print("PeriodIndex...\n", periodIndex)

요일(dayofweek) 구하기

PeriodIndex 객체에서 요일을 가져옵니다. 요일은 월요일=0, 화요일=1 ... 일요일=6 형태의 정수로 표시됩니다.

print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

전체 예제 코드

다음은 지금까지의 내용을 모두 포함한 완전한 코드입니다.

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)

# PeriodIndex에서 '일(day)' 값 출력
print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)

# PeriodIndex에서 요일 출력
# 요일은 월요일=0, 화요일=1 ... 일요일=6으로 표시됩니다.
print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

실행 결과

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

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>

The number of days from the PeriodIndex...
Int64Index([25, 30, 20, 15, 12, 18], dtype='int64')

Days of the week from the PeriodIndex...
Int64Index([2, 2, 4, 2, 5, 6], dtype='int64')

정리

이처럼 pandas.PeriodIndex()로 날짜 데이터를 기간 인덱스로 변환한 뒤, dayofweek 속성을 사용하면 각 날짜가 무슨 요일인지 손쉽게 숫자 형태(월=0 ~ 일=6)로 확인할 수 있습니다. 또한 day 속성으로 일(day) 값만 추출하거나, freq 속성으로 설정된 빈도를 확인하는 것도 가능합니다.