TimeDeltaIndex를 초(second) 빈도로 반올림하려면 Pandas의 TimeDeltaIndex.round() 메서드를 사용합니다. 이때 freq 매개변수에 'S'(초) 값을 지정하면 됩니다.
필요한 라이브러리 가져오기
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
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 출력하기
생성된 TimedeltaIndex를 화면에 표시합니다.
print("TimedeltaIndex...\n", tdIndex)초 빈도로 반올림 수행
TimeDeltaIndex 값에 대해 초 빈도 기준으로 반올림 연산을 수행합니다. 초 빈도를 나타내기 위해 freq 매개변수에 'S'를 사용했습니다.
print("\nPerforming round operation with seconds frequency...\n",
tdIndex.round(freq='S'))전체 예제 코드
다음은 지금까지의 내용을 모두 포함한 완전한 코드입니다.
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)
# 초 빈도 기준으로 반올림 연산 수행
# 초 빈도를 위해 'S' 사용
print("\nPerforming round operation with seconds frequency...\n",
tdIndex.round(freq='S'))실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
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
Performing round operation with seconds frequency...
TimedeltaIndex(['10 days 05:02:00', '0 days 22:39:20', '2 days 07:08:02',
'0 days 21:15:46'],
dtype='timedelta64[ns]', freq=None)결과 해석
출력 결과를 보면 밀리초·마이크로초·나노초 단위의 소수점 이하 값들이 모두 제거되고 가장 가까운 초 단위로 반올림된 것을 확인할 수 있습니다. 예를 들어 0 days 22:39:19.999999는 0 days 22:39:20으로 올림 처리되었고, 2 days 07:08:02.000045는 2 days 07:08:02로 내림 처리되었습니다.