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

Python Pandas – TimeDeltaIndex 객체 생성 방법

TimeDeltaIndex 객체란?

Pandas에서 시간 간격(time delta) 데이터를 인덱스로 다뤄야 할 때는 pandas.TimedeltaIndex() 메서드를 사용하면 됩니다. 이 메서드를 활용하면 두 시점 사이의 차이를 나타내는 timedelta 값을 하나의 인덱스 객체로 손쉽게 만들 수 있습니다.

기본 사용법

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

import pandas as pd

이어서 TimeDeltaIndex 객체를 생성합니다. 아래 예제에서는 'data' 매개변수에 timedelta 형식의 문자열 목록을 전달했습니다.

tdIndex = pd.TimedeltaIndex(data =['10 day 5h 2 min 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])

생성된 TimedeltaIndex를 화면에 출력해 봅니다.

print("TimedeltaIndex...\n", tdIndex)

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 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])

# TimedeltaIndex 출력
print("TimedeltaIndex...\n", tdIndex)

# TimeDeltaIndex의 각 요소에서 일(day) 수 추출
print("\nThe number of days from the TimeDeltaIndex object...\n", tdIndex.days)

# TimeDeltaIndex의 각 요소에서 초(second) 수 추출
print("\nThe number of seconds from the TimeDeltaIndex object...\n", tdIndex.seconds)

# TimeDeltaIndex의 각 요소에서 마이크로초(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:00.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([18120, 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      0         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

정리

pandas.TimedeltaIndex()를 사용하면 다양한 형식의 timedelta 문자열을 하나의 인덱스 객체로 변환할 수 있습니다. 또한 .days, .seconds, .microseconds 속성으로 특정 단위의 값을 추출하고, .components 속성으로 일·시간·분·초·밀리초·마이크로초·나노초 구성 요소를 한눈에 파악할 수 있어 시간 간격 데이터를 분석할 때 매우 유용합니다.