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

Python Pandas – DateTimeIndex를 분(Minute) 단위로 반올림하는 방법

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

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

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

import pandas as pd

DateTimeIndex 생성하기

총 5개의 기간(period)을 가지며, 빈도는 초 단위(45초)로 설정하고 시간대(timezone)는 'Australia/Adelaide'로 지정한 DatetimeIndex를 생성해 보겠습니다.

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

생성된 DateTimeIndex를 출력하여 확인합니다.

print("DateTimeIndex...\n", datetimeindex)

분 단위 반올림 수행하기

이제 DateTimeIndex에 대해 분 단위 반올림 연산을 수행합니다. 분(minute) 빈도를 나타내기 위해 freq 매개변수에 'T'를 사용합니다.

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

전체 예제 코드

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

import pandas as pd

# 총 5개의 기간과 초(s) 단위 빈도를 가지는 DatetimeIndex 생성
# 시간대는 Australia/Adelaide로 설정
datetimeindex = pd.date_range('2021-09-29 07:00', periods=5, tz='Australia/Adelaide', freq='45s')

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

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

# 분(minute) 값 추출
res = datetimeindex.minute

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

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

실행 결과

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

DateTimeIndex...
DatetimeIndex(['2021-09-29 07:00:00+09:30', '2021-09-29 07:00:45+09:30',
'2021-09-29 07:01:30+09:30', '2021-09-29 07:02:15+09:30',
'2021-09-29 07:03:00+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='45S')
DateTimeIndex frequency...
<45 * Seconds>

The minute from DateTimeIndex...
Int64Index([0, 0, 1, 2, 3], dtype='int64')
Performing round operation with minute frequency...
DatetimeIndex(['2021-09-29 07:00:00+09:30', '2021-09-29 07:01:00+09:30',
'2021-09-29 07:02:00+09:30', '2021-09-29 07:02:00+09:30',
'2021-09-29 07:03:00+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

결과 해석

출력 결과를 보면 원래의 DateTimeIndex는 45초 간격으로 생성되어 있으며, 각 타임스탬프의 초 단위 값이 다양하게 분포되어 있습니다. round(freq='T')를 적용한 후에는 모든 타임스탬프가 가장 가까운 분 단위로 반올림된 것을 확인할 수 있습니다.

예를 들어 '2021-09-29 07:00:45'는 45초이므로 가장 가까운 분인 '07:01:00'으로 반올림되고, '2021-09-29 07:02:15'는 15초이므로 내림되어 '07:02:00'으로 처리됩니다. 이처럼 Pandas의 round() 메서드는 표준 반올림 규칙(30초를 기준으로)에 따라 시간 값을 정렬할 때 매우 유용하게 사용됩니다.