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

Python Pandas - TimeDeltaIndex를 시리즈로 변환하고 결과 시리즈의 인덱스 설정하기

Pandas에서 TimeDeltaIndex 객체를 시리즈(Series)로 변환하려면 to_series() 메서드를 사용합니다. 이때 index 매개변수를 활용하면 변환된 결과 시리즈에 원하는 인덱스를 직접 설정할 수 있습니다.

1. 라이브러리 임포트

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

import pandas as pd

2. TimeDeltaIndex 객체 생성

'data' 매개변수를 사용해 timedelta 형식의 데이터를 지정하여 TimeDeltaIndex 객체를 생성합니다.

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)

3. TimeDeltaIndex를 시리즈로 변환하고 인덱스 설정

TimeDeltaIndex를 시리즈로 변환하면서 결과 시리즈의 인덱스를 새롭게 지정합니다. 아래 예제에서는 'index' 매개변수를 통해 'Date1'부터 'Date4'까지의 인덱스를 설정했습니다.

print("\nTimeDeltaIndex to series with new index...\n",
tdIndex.to_series(index=['Date1','Date2','Date3','Date4']))

전체 예제 코드

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

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 구성 요소(components)를 데이터프레임으로 반환
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를 시리즈로 변환하고 결과 시리즈의 인덱스 설정
# 'index' 매개변수를 사용해 인덱스를 지정
print("\nTimeDeltaIndex to series with new index...\n",
tdIndex.to_series(index=['Date1','Date2','Date3','Date4']))

실행 결과

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

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 with new index...
Date1 10 days 05:02:00.000003010
Date2 0 days 22:39:19.999999
Date3 2 days 07:08:02.000045
Date4 0 days 21:15:45.999999
dtype: timedelta64[ns]