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

Python Pandas – DateTimeIndex에서 초 빈도로 Ceil(올림) 연산 수행하기

Pandas에서 DateTimeIndex에 대해 초(seconds) 단위 빈도로 ceil(올림) 연산을 수행하려면 DateTimeIndex.ceil() 메서드를 사용하면 됩니다. 이 메서드는 타임스탬프의 나노초 이하 값을 지정한 빈도 단위로 올려 반올림(올림)해 줍니다. 초 단위 빈도를 적용할 때는 freq 매개변수에 'S' 값을 전달합니다.

1단계: 필요한 라이브러리 임포트

먼저 pandas 라이브러리를 불러옵니다.

import pandas as pd

2단계: DatetimeIndex 생성

시작 시점 '2021-10-18 07:20:32.261811624'부터 총 5개의 타임스탬프를 40초 간격으로 생성하고, 시간대(timezone)는 'Australia/Adelaide'로 설정합니다.

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

3단계: DateTimeIndex 확인 및 ceil 연산 적용

생성된 DateTimeIndex를 출력한 후, freq='S' 옵션으로 ceil 연산을 적용합니다.

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

print("\n초 빈도로 ceil 연산 수행...\n", datetimeindex.ceil(freq='S'))

전체 예제 코드

아래는 위 과정을 모두 포함한 완전한 예제 코드입니다.

import pandas as pd

# 기간(periods) 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)

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

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

# 초 빈도('S')로 DateTimeIndex에 ceil 연산 수행
print("\nPerforming ceil operation with seconds frequency...\n",
datetimeindex.ceil(freq='S'))

실행 결과

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

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>

The second from DateTimeIndex...
Int64Index([32, 12, 52, 32, 12], dtype='int64')

Performing ceil operation with seconds frequency...
DatetimeIndex(['2021-10-18 07:20:33+10:30', '2021-10-18 07:21:13+10:30',
'2021-10-18 07:21:53+10:30', '2021-10-18 07:22:33+10:30',
'2021-10-18 07:23:13+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

결과 해석

출력 결과를 보면 원본 타임스탬프에 소수점 이하 나노초 값(0.261811624초)이 포함되어 있었습니다. ceil(freq='S')를 적용하면 각 타임스탬프가 가장 가까운 다음 초 단위 값으로 올림됩니다. 예를 들어 07:20:32.26181162407:20:33으로 변환됩니다. 또한 원본 인덱스의 빈도 정보(40S)는 유지되지만, ceil 연산이 적용된 새 인덱스는 freq=None이 되는 점도 참고하세요.