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

Python Pandas – 밀리초(ms) 빈도로 DateTimeIndex 반올림하는 방법

Pandas에서 DateTimeIndex를 밀리초 단위로 반올림하려면 DateTimeIndex.round() 메서드를 사용합니다. 밀리초 빈도로 반올림할 때는 freq 매개변수에 'ms' 값을 지정하면 됩니다.

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

import pandas as pd

1단계: DatetimeIndex 생성

이제 기간(period)은 5개, 빈도는 초 단위('28s')인 DatetimeIndex를 생성해 보겠습니다. 시간대는 호주 애들레이드(Australia/Adelaide)로 설정했습니다.

datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='28s')

2단계: 밀리초 빈도로 반올림 수행

생성된 DateTimeIndex에 대해 round() 메서드를 호출하고, freq 매개변수에 'ms'(밀리초)를 전달하여 반올림을 수행합니다.

print("\n밀리초 빈도로 반올림 연산 수행...\n",
datetimeindex.round(freq='ms'))

전체 예제 코드

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

import pandas as pd

# 기간 5개, 빈도는 초(s) 단위인 DatetimeIndex 생성
# 시간대는 Australia/Adelaide로 설정
datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='28s')

# DateTimeIndex 출력
print("DateTimeIndex...\n", datetimeindex)

# DateTimeIndex의 빈도 출력
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# 밀리초 빈도로 반올림 연산 수행
# 밀리초 빈도에는 'ms' 사용
print("\nPerforming round operation with milliseconds frequency...\n",
datetimeindex.round(freq='ms'))

실행 결과

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

DateTimeIndex...
DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30',
'2021-09-29 07:21:00.261811624+09:30',
'2021-09-29 07:21:28.261811624+09:30',
'2021-09-29 07:21:56.261811624+09:30',
'2021-09-29 07:22:24.261811624+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='28S')
DateTimeIndex frequency...
<28 * Seconds>

Performing round operation with milliseconds frequency...
DatetimeIndex(['2021-09-29 07:20:32.262000+09:30',
'2021-09-29 07:21:00.262000+09:30',
'2021-09-29 07:21:28.262000+09:30',
'2021-09-29 07:21:56.262000+09:30',
'2021-09-29 07:22:24.262000+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

결과 분석

출력 결과를 보면 원래 나노초(nanosecond)까지 표현되던 타임스탬프 값들이 밀리초 단위로 반올림된 것을 확인할 수 있습니다. 예를 들어 07:20:32.26181162407:20:32.262000으로 변경되었습니다. 또한 반올림 연산 후에는 새로운 DatetimeIndex가 반환되며, 이때 원래의 빈도(freq) 정보는 유지되지 않고 None으로 설정됩니다.