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

Python Pandas - DateTimeIndex에서 주파수(freq)를 문자열로 추출하는 방법

Pandas의 DateTimeIndex.freqstr 속성을 사용하면 DateTimeIndex에서 주파수(frequency) 객체를 문자열 형태로 손쉽게 추출할 수 있습니다.

기본 사용법

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

import pandas as pd

기간(periods)은 6, 주파수는 'D'(일 단위)로 설정하고, 시간대(timezone)를 호주 애들레이드로 지정하여 DatetimeIndex를 생성합니다.

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

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

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

이어서 주파수를 문자열 형태로 출력합니다.

print("DateTimeIndex frequency as string...\n", datetimeindex.freqstr)

전체 예제 코드

지금까지의 내용을 하나로 정리한 전체 코드는 다음과 같습니다.

import pandas as pd

# 기간 6, 주파수 'D'(일 단위)로 DatetimeIndex 생성
# 시간대는 Australia/Adelaide로 설정
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')

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

# DateTimeIndex의 주파수 객체 출력
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# 주파수를 문자열 형태로 출력
print("DateTimeIndex frequency as string...\n", datetimeindex.freqstr)

실행 결과

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

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+10:30', '2021-10-21 02:30:50+10:30',
'2021-10-22 02:30:50+10:30', '2021-10-23 02:30:50+10:30',
'2021-10-24 02:30:50+10:30', '2021-10-25 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='D')

DateTimeIndex frequency...
<Day>

DateTimeIndex frequency as string...
D

freq와 freqstr의 차이점

freq 속성은 주파수 객체 자체(예: <Day>)를 반환하는 반면, freqstr 속성은 해당 객체를 문자열(예: 'D')로 변환하여 반환합니다. 따라서 로그 출력이나 다른 라이브러리와의 연동처럼 문자열 형태의 주파수 정보가 필요한 경우에는 freqstr을 사용하는 것이 훨씬 편리합니다. 참고로 주파수가 설정되지 않은 DatetimeIndex에 freqstr을 호출하면 None이 반환됩니다.