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

Python Pandas – TimeDeltaIndex 객체에서 DataFrame 생성 후 결과 열 이름 재정의하기

TimeDeltaIndex 객체에서 DataFrame을 생성하려면 to_frame() 메서드를 사용하면 됩니다. 이때 name 매개변수를 함께 지정하면 결과 열의 이름을 원하는 값으로 자유롭게 재정의할 수 있습니다.

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

import pandas as pd

TimeDeltaIndex 객체를 생성합니다. 'data' 매개변수를 통해 timedelta 형식의 데이터를 설정했습니다.

tdIndex = pd.TimedeltaIndex(data =['4 day 8h 20min 35us 45ns', '+17:42:19.999999',
'9 day 3h 08:16:02.000055', '+22:35:25.000075'])

생성된 TimedeltaIndex를 출력해 내용을 확인합니다.

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

이제 TimeDeltaIndex 객체에서 DataFrame을 생성합니다. 'index=False' 매개변수를 지정하면 반환되는 DataFrame에 기존 인덱스가 설정되지 않으며, 'name' 매개변수를 사용해 결과 열의 이름을 'DateTimeData'로 재정의했습니다.

print("\nTimeDeltaIndex to DataFrame...\n", tdIndex.to_frame(index=False, name = 'DateTimeData'))

전체 예제 코드

지금까지 설명한 내용을 하나로 정리한 전체 코드는 다음과 같습니다.

import pandas as pd

# TimeDeltaIndex 객체 생성
# 'data' 매개변수로 timedelta 형식의 데이터를 설정합니다.
tdIndex = pd.TimedeltaIndex(data =['4 day 8h 20min 35us 45ns', '+17:42:19.999999',
'9 day 3h 08:16:02.000055', '+22:35:25.000075'])

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

# TimeDelta 구성 요소(일, 시, 분, 초 등)를 담은 DataFrame 반환
print("\nThe Dataframe of the components of TimeDeltas...\n", tdIndex.components)

# TimeDeltaIndex 객체에서 DataFrame 생성
# 'index=False'로 설정해 기존 인덱스가 반환되는 DataFrame에 적용되지 않도록 합니다.
# 'name' 매개변수를 사용해 결과 열의 이름을 재정의합니다.
print("\nTimeDeltaIndex to DataFrame...\n", tdIndex.to_frame(index=False, name = 'DateTimeData'))

실행 결과

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

TimedeltaIndex...
TimedeltaIndex(['4 days 08:20:00.000035045', '0 days 17:42:19.999999',
'9 days 11:16:02.000055', '0 days 22:35:25.000075'],
dtype='timedelta64[ns]', freq=None)

The Dataframe of the components of TimeDeltas...
   days hours minutes seconds milliseconds microseconds nanoseconds
0    4     8      20      0            0           35           45
1    0    17      42     19          999          999            0
2    9    11      16      2            0           55            0
3    0    22      35     25            0           75            0

TimeDeltaIndex to DataFrame...
   DateTimeData
0 4 days 08:20:00.000035045
1 0 days 17:42:19.999999
2 9 days 11:16:02.000055
3 0 days 22:35:25.000075