DateTimeIndex에서 DataFrame을 생성하려면 datetimeindex.to_frame() 메서드를 사용합니다. 이때 name 매개변수를 지정하면 생성되는 결과 열의 이름을 원하는 값으로 자유롭게 재정의할 수 있습니다.
라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
DatetimeIndex 생성
기간(periods)은 5, 빈도(freq)는 'S', 즉 초 단위로 지정하여 DatetimeIndex를 생성합니다. 타임존은 호주 애들레이드('Australia/Adelaide')로 설정했습니다.
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
DateTimeIndex 확인 및 DataFrame 변환
생성된 DateTimeIndex를 출력해 내용을 확인합니다.
print("DateTimeIndex...\n", datetimeindex)
to_frame() 메서드에 index=False를 전달하면 원래 인덱스가 반환되는 DataFrame에는 설정되지 않습니다. 또한 name 매개변수를 사용해 결과 열의 이름을 'DateTimeData'로 재정의했습니다.
print("\nDateTimeIndex to DataFrame...\n",
datetimeindex.to_frame(index=False, name='DateTimeData'))
전체 예제 코드
import pandas as pd
# periods는 5, freq는 'S'(초 단위)인 DatetimeIndex 생성
# 타임존은 Australia/Adelaide로 설정
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
# DateTimeIndex 출력
print("DateTimeIndex...\n", datetimeindex)
# DateTimeIndex의 빈도 출력
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)
# DateTimeIndex에서 DataFrame 생성
# index=False → 반환되는 DataFrame에 원본 인덱스 미설정
# name 매개변수 → 결과 열의 이름 재정의
print("\nDateTimeIndex to DataFrame...\n",
datetimeindex.to_frame(index=False, name='DateTimeData'))
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30',
'2021-10-18 07:21:12.261811624+10:30',
'2021-10-18 07:21:52.261811624+10:30',
'2021-10-18 07:22:32.261811624+10:30',
'2021-10-18 07:23:12.261811624+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='40S')
DateTimeIndex frequency...
<40 * Seconds>
DateTimeIndex to DataFrame...
DateTimeData
0 2021-10-18 07:20:32.261811624+10:30
1 2021-10-18 07:21:12.261811624+10:30
2 2021-10-18 07:21:52.261811624+10:30
3 2021-10-18 07:22:32.261811624+10:30
4 2021-10-18 07:23:12.261811624+10:30
주요 매개변수 정리
- index: 기본값은 True이며, 이 경우 인덱스가 DataFrame의 열로 포함됩니다. False로 설정하면 인덱스 없이 데이터 열만 반환됩니다.
- name: 결과 DataFrame의 열 이름을 직접 지정합니다. 생략하면 인덱스의 name 속성이 그대로 사용됩니다.
참고 사항
pd.date_range()의 freq 값을 변경하면 타임스탬프의 간격을 조절할 수 있습니다. 위 예제에서는 '40S'로 지정해 40초 간격의 시계열 데이터를 생성했습니다. 이렇게 만든 DateTimeIndex는 시계열 데이터 분석의 출발점으로 다양하게 활용할 수 있습니다.