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

Python Pandas – TimeDeltaIndex를 시리즈로 변환하고 결과 시리즈의 이름 설정하기

Pandas에서 to_series() 메서드를 사용하면 TimeDeltaIndex 객체를 손쉽게 시리즈(Series)로 변환할 수 있습니다. 이때 name 매개변수를 지정하면 결과로 생성되는 시리즈에 원하는 이름을 부여할 수 있습니다.

필요한 라이브러리 가져오기

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

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를 화면에 출력해 확인해 보겠습니다.

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

시리즈 변환 및 이름 설정

TimeDeltaIndex를 시리즈로 변환하면서 결과 시리즈의 이름을 지정합니다. 시리즈의 이름은 'name' 매개변수를 통해 설정합니다.

print("\nTimeDeltaIndex to series...\n", tdIndex.to_series(name="DateTime Data"))

전체 예제 코드

지금까지 설명한 내용을 모두 포함한 전체 코드는 다음과 같습니다.

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를 시리즈로 변환하고 결과 시리즈의 이름 설정
# 시리즈 이름은 'name' 매개변수로 지정
print("\nTimeDeltaIndex to series...\n", tdIndex.to_series(name="DateTime Data"))

실행 결과

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

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
Name: DateTime Data, dtype: timedelta64[ns]

정리

이처럼 Pandas의 to_series() 메서드를 활용하면 TimeDeltaIndex를 간단히 시리즈 형태로 변환할 수 있으며, name 매개변수를 사용해 결과 시리즈에 의미 있는 이름을 부여함으로써 이후 데이터 분석 작업에서 가독성과 활용도를 높일 수 있습니다.