TimedeltaIndex의 구성 요소(components)를 데이터프레임(DataFrame) 형태로 반환하려면 TimedeltaIndex.components 속성을 사용합니다. 이 속성은 일(days), 시간(hours), 분(minutes), 초(seconds), 밀리초(milliseconds), 마이크로초(microseconds), 나노초(nanoseconds)와 같은 각 시간 단위별 값을 열(column)로 정리한 데이터프레임을 반환해 줍니다.
1. 필요한 라이브러리 가져오기
먼저 Pandas 라이브러리를 임포트합니다.
import pandas as pd
2. TimedeltaIndex 객체 생성
data 매개변수에 timedelta 형식의 문자열 리스트를 전달하여 TimedeltaIndex 객체를 생성합니다.
tdIndex = pd.TimedeltaIndex(data =['10 day 5h 2 min 35s 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])
3. TimedeltaIndex 출력하기
생성된 TimedeltaIndex 객체를 화면에 출력해 내용을 확인합니다.
print("TimedeltaIndex...\n", tdIndex)
4. 구성 요소 데이터프레임 반환하기
components 속성에 접근하면 각 Timedelta 값이 어떤 시간 단위들로 이루어져 있는지 한눈에 파악할 수 있는 데이터프레임을 얻을 수 있습니다.
print("\nThe Dataframe of the components of TimeDeltas...\n", tdIndex.components)
전체 예제 코드
다음은 지금까지 설명한 내용을 모두 포함한 전체 코드입니다.
import pandas as pd
# TimeDeltaIndex 객체 생성
# 'data' 매개변수를 사용해 timedelta 형식의 데이터를 설정했습니다.
tdIndex = pd.TimedeltaIndex(data =['10 day 5h 2 min 35s 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])
# TimedeltaIndex 출력
print("TimedeltaIndex...\n", tdIndex)
# 각 요소에서 일(day) 수 표시
print("\nThe number of days from the TimeDeltaIndex object...\n", tdIndex.days)
# 각 요소에서 초(second) 수 표시
print("\nThe number of seconds from the TimeDeltaIndex object...\n", tdIndex.seconds)
# 각 요소에서 마이크로초(microsecond) 수 표시
print("\nThe number of microseconds from the TimeDeltaIndex object...\n", tdIndex.microseconds)
# TimeDelta의 구성 요소 데이터프레임 반환
# 구성 요소에는 일, 시간, 분, 초, 밀리초, 마이크로초, 나노초가 포함됩니다.
print("\nThe Dataframe of the components of TimeDeltas...\n", tdIndex.components)
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
TimedeltaIndex... TimedeltaIndex(['10 days 05:02:35.000003010', '0 days 22:39:19.999999', '2 days 07:08:02.000045', '0 days 21:15:45.999999'], dtype='timedelta64[ns]', freq=None) The number of days from the TimeDeltaIndex object... Int64Index([10, 0, 2, 0], dtype='int64') The number of seconds from the TimeDeltaIndex object... Int64Index([18155, 81559, 25682, 76545], dtype='int64') The number of microseconds from the TimeDeltaIndex object... Int64Index([3, 999999, 45, 999999], dtype='int64') The Dataframe of the components of TimeDeltas... days hours minutes seconds milliseconds microseconds nanoseconds 0 10 5 2 35 0 3 10 1 0 22 39 19 999 999 0 2 2 7 8 2 0 45 0 3 0 21 15 45 999 999 0
정리
days, seconds, microseconds 같은 개별 속성은 특정 단위의 값만 따로 확인할 때 유용하고, components 속성은 모든 시간 단위를 하나의 데이터프레임으로 한 번에 확인할 수 있어 시간 데이터를 분석하거나 디버깅할 때 특히 편리합니다.