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

Python Pandas – DateTimeIndex를 초(S) 단위 빈도로 반올림하는 방법

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

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

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

import pandas as pd

DatetimeIndex 생성하기

아래 코드는 시작 시점을 기준으로 28초 간격의 데이터를 5개 생성하며, 시간대(timezone)는 'Australia/Adelaide'로 설정한 DatetimeIndex를 만듭니다.

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

초 단위 빈도로 반올림 수행하기

DatetimeIndex에 대해 초 단위 빈도로 반올림 연산을 적용합니다. 초 빈도를 나타내는 값은 'S'입니다.

print("\nPerforming round operation with seconds frequency...\n",
datetimeindex.round(freq='S'))

전체 예제 코드

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

import pandas as pd

# period 5, frequency s(초)인 DatetimeIndex 생성
# timezone은 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)

# 초(second) 값 추출
res = datetimeindex.second

# 초 값만 출력
print("\nThe second from DateTimeIndex...\n", res)

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

실행 결과

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

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>

The second from DateTimeIndex...
Int64Index([32, 0, 28, 56, 24], dtype='int64')

Performing round operation with seconds frequency...
DatetimeIndex(['2021-09-29 07:20:32+09:30', '2021-09-29 07:21:00+09:30',
'2021-09-29 07:21:28+09:30', '2021-09-29 07:21:56+09:30',
'2021-09-29 07:22:24+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

결과 해석

출력 결과를 보면 원래 DatetimeIndex는 나노초(nanosecond) 단위까지 포함된 정밀한 타임스탬프를 가지고 있지만, round(freq='S')를 적용한 후에는 모든 값이 가장 가까운 초 단위로 반올림되어 소수점 이하가 제거된 것을 확인할 수 있습니다. 또한 .second 속성을 사용하면 각 타임스탬프에서 초 값만 별도로 추출할 수 있습니다.