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

Python Pandas - TimeDeltaIndex를 마이크로초(us) 빈도로 반올림하는 방법

TimeDeltaIndex를 마이크로초 빈도로 반올림하기

Python의 Pandas 라이브러리에서 TimeDeltaIndex를 마이크로초(us) 단위로 반올림하려면 TimeDeltaIndex.round() 메서드를 사용하면 됩니다. 이때 freq 매개변수에 'us'(마이크로초) 값을 지정하면 됩니다.

round() 메서드는 지정한 빈도(frequency)를 기준으로 각 timedelta 값을 가장 가까운 값으로 반올림해 줍니다. 예를 들어 'us'를 지정하면 나노초(ns) 단위의 값들이 마이크로초 단위로 정리됩니다.

1단계: 필요한 라이브러리 임포트

먼저 pandas 라이브러리를 임포트합니다.

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', '+07:20:32.261811624'])

3단계: TimeDeltaIndex 출력하기

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

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

4단계: 마이크로초 빈도로 반올림 수행

freq 매개변수에 'us'를 지정하여 마이크로초 빈도 기준의 반올림 연산을 실행합니다.

print("\nPerforming round operation with microseconds frequency...\n",
tdIndex.round(freq='us'))

전체 예제 코드

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

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', '+07:20:32.261811624'])

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

# TimeDelta 구성 요소(components)를 데이터프레임 형태로 반환
print("\nThe Dataframe of the components of TimeDeltas...\n", tdIndex.components)

# 마이크로초 빈도('us')를 사용한 반올림 연산 수행
print("\nPerforming round operation with microseconds frequency...\n",
tdIndex.round(freq='us'))

실행 결과

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

TimedeltaIndex...
TimedeltaIndex(['10 days 05:02:00.000003010', '0 days 22:39:19.999999',
'2 days 07:08:02.000045', '0 days 07:20:32.261811624'],
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     7      20      32          261          811          624

Performing round operation with microseconds frequency...
TimedeltaIndex(['10 days 05:02:00.000003', '0 days 22:39:19.999999',
'2 days 07:08:02.000045', '0 days 07:20:32.261812'],
dtype='timedelta64[ns]', freq=None)

결과 분석

출력 결과를 살펴보면 반올림 연산의 효과를 명확히 확인할 수 있습니다.

  • 첫 번째 값 '10 days 05:02:00.000003010'은 나노초 단위 값(010ns)이 제거되어 '10 days 05:02:00.000003'으로 반올림되었습니다.
  • 두 번째와 세 번째 값은 이미 마이크로초 단위에 맞게 표현되어 있어 변경되지 않았습니다.
  • 네 번째 값 '0 days 07:20:32.261811624'는 나노초 부분(624ns)이 반영되어 '0 days 07:20:32.261812'로 올림 처리되었습니다.

이처럼 freq='us' 옵션을 사용하면 TimeDeltaIndex의 값을 손쉽게 마이크로초 단위로 정규화할 수 있으며, 시간 데이터의 정밀도를 일관되게 유지해야 하는 데이터 전처리 작업에서 유용하게 활용할 수 있습니다.