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

Python Pandas - TimeDeltaIndex에서 시리즈(Series) 생성하기

Pandas에서 TimeDeltaIndex 객체를 시리즈(Series)로 변환하려면 to_series() 메서드를 사용하면 됩니다. 이 메서드는 인덱스의 각 요소를 값으로 가지는 새로운 시리즈를 반환하며, 기존 인덱스는 그대로 유지됩니다.

필요한 라이브러리 불러오기

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

import pandas as pd

TimeDeltaIndex 객체 생성

이제 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를 시리즈로 변환

생성된 TimeDeltaIndex를 to_series() 메서드를 사용해 시리즈로 변환합니다.

print("\nTimeDeltaIndex to series...\n", tdIndex.to_series())

전체 예제 코드

다음은 위 과정을 모두 포함한 전체 코드입니다.

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)

# TimeDeltaIndex를 datetime.timedelta 객체의 ndarray로 변환
print("\nReturn TimeDeltaIndex as object ndarray of datetime.datetime objects...\n",
tdIndex.to_pytimedelta())

# TimeDeltaIndex를 시리즈로 변환
print("\nTimeDeltaIndex to series...\n", tdIndex.to_series())

출력 결과

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

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 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

Return TimeDeltaIndex as object ndarray of datetime.datetime objects...
[datetime.timedelta(days=10, seconds=18120, microseconds=3)
datetime.timedelta(seconds=81559, microseconds=999999)
datetime.timedelta(days=2, seconds=25682, microseconds=45)
datetime.timedelta(seconds=76545, microseconds=999999)]

TimeDeltaIndex to series...
10 days 05:02:00.000003010 10 days 05:02:00.000003010
0 days 22:39:19.999999 0 days 22:39:19.999999
2 days 07:08:02.000045 2 days 07:08:02.000045
0 days 21:15:45.999999 0 days 21:15:45.999999
dtype: timedelta64[ns]

정리

이 예제에서 확인할 수 있듯이, to_series() 메서드는 TimeDeltaIndex의 각 timedelta 값을 값(value)으로 하고, 원래 인덱스 레이블을 그대로 유지하는 시리즈를 반환합니다. 또한 components 속성을 활용하면 일(days), 시(hours), 분(minutes), 초(seconds), 밀리초(milliseconds), 마이크로초(microseconds), 나노초(nanoseconds) 단위의 구성 요소를 데이터프레임 형태로 손쉽게 확인할 수 있습니다. 이러한 기능들은 시간 간격 데이터를 다루는 시계열 분석 작업에서 매우 유용하게 활용됩니다.