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

Python Pandas DateTimeIndex.ceil() – 지정된 주파수로 시간 올림 처리하는 방법

개요

Pandas에서 DateTimeIndex의 날짜·시간 값을 지정된 주파수(freq) 단위로 올림(ceil) 처리하려면 DateTimeIndex.ceil() 메서드를 사용합니다. 이 메서드는 각 타임스탬프를 지정한 시간 단위의 가장 가까운 위쪽 경계로 반올림(올림)해 줍니다.

주파수는 freq 매개변수를 통해 설정하며, 초('S'), 밀리초('ms'), 마이크로초('us') 등 다양한 시간 단위를 지정할 수 있습니다.

기본 사용 절차

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

import pandas as pd

다음으로 기간(periods)이 5이고 주파수가 'S'(초)인 DatetimeIndex를 생성합니다. 여기서는 타임존을 'Australia/Adelaide'로 지정하고, 40초 간격('40S')으로 생성했습니다.

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')

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

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

마지막으로 지정된 주파수('us', 즉 마이크로초)를 기준으로 ceil 연산을 수행합니다.

print("\nPerforming ceil operation...\n",
datetimeindex.ceil(freq='us'))

전체 예제 코드

아래는 위 과정을 하나로 정리한 전체 코드입니다.

import pandas as pd

# 기간 5, 주파수 'S'(초)인 DatetimeIndex 생성
# 타임존은 Australia/Adelaide로 지정
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')

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

# DateTimeIndex의 주파수 출력
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# 지정된 주파수로 ceil 연산 수행
print("\nPerforming ceil operation...\n",
datetimeindex.ceil(freq='us'))

실행 결과

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

DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30',
'2021-10-18 07:21:12.261811624+10:30',
'2021-10-18 07:21:52.261811624+10:30',
'2021-10-18 07:22:32.261811624+10:30',
'2021-10-18 07:23:12.261811624+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='40S')
DateTimeIndex frequency...
<40 * Seconds>

Performing ceil operation...
DatetimeIndex(['2021-10-18 07:20:32.261812+10:30',
'2021-10-18 07:21:12.261812+10:30',
'2021-10-18 07:21:52.261812+10:30',
'2021-10-18 07:22:32.261812+10:30',
'2021-10-18 07:23:12.261812+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

결과 해석

출력 결과를 보면 원래 타임스탬프는 나노초(nanosecond) 단위까지 표현되어 있지만(예: .261811624), freq='us'(마이크로초)로 ceil 연산을 수행한 후에는 소수점 아래 여섯 자리(.261812)까지만 남고 나머지는 올림 처리된 것을 확인할 수 있습니다.

또한 ceil 연산 후에는 인덱스의 freq 속성이 None으로 변경되는 점도 참고하세요. 이는 새로운 인덱스에 고정된 주파수 정보가 유지되지 않기 때문입니다.

참고: 유사한 메서드

DateTimeIndex에는 ceil 외에도 다음과 같은 유사한 메서드가 제공됩니다.

  • floor(freq): 지정된 주파수 단위로 내림 처리
  • round(freq): 지정된 주파수 단위로 반올림 처리

데이터 전처리 시 시간 데이터를 특정 단위로 정규화해야 할 때 이 세 가지 메서드를 상황에 맞게 활용하면 유용합니다.