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

Python Pandas – DateTimeIndex에서 밀리초(ms) 빈도로 floor(내림) 연산 수행하는 방법

DateTimeIndex에 대해 밀리초(ms) 단위의 내림(floor) 연산을 수행하려면 DateTimeIndex.floor() 메서드를 사용하면 됩니다. 이때 밀리초 빈도를 지정하기 위해 freq 매개변수에 'ms' 값을 전달합니다.

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

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

import pandas as pd

2단계: DateTimeIndex 생성

시작 시점을 기준으로 총 5개의 타임스탬프를 가지며, 간격은 40초('40S'), 시간대는 호주 애들레이드(Australia/Adelaide)로 설정된 DatetimeIndex를 생성합니다.

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

3단계: DateTimeIndex 출력

생성된 DateTimeIndex를 화면에 표시해 확인합니다.

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

4단계: 밀리초 빈도로 floor 연산 수행

밀리초(ms) 빈도를 기준으로 DateTimeIndex의 날짜·시간 값에 내림 연산을 적용합니다. 밀리초 빈도를 나타내기 위해 freq 인자에 'ms'를 사용했습니다.

print("\nPerforming floor operation with milliseconds frequency...\n",
datetimeindex.floor(freq='ms'))

전체 예제 코드

지금까지의 과정을 하나로 정리한 전체 코드는 다음과 같습니다.

import pandas as pd

# 주기 5개, 빈도 40초('40S')인 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의 빈도(freq) 출력
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# 밀리초(ms) 빈도로 floor(내림) 연산 수행
print("\nPerforming floor operation with milliseconds frequency...\n",
datetimeindex.floor(freq='ms'))

실행 결과

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

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 floor operation with milliseconds frequency...
DatetimeIndex(['2021-10-18 07:20:32.261000+10:30',
'2021-10-18 07:21:12.261000+10:30',
'2021-10-18 07:21:52.261000+10:30',
'2021-10-18 07:22:32.261000+10:30',
'2021-10-18 07:23:12.261000+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

결과 해석

출력 결과를 보면 원래 나노초(nanosecond)까지 포함되어 있던 타임스탬프가 .261000, 즉 밀리초 단위까지만 남고 그 이하 자릿수가 잘려나간 것을 확인할 수 있습니다. 이것이 바로 floor(freq='ms')가 밀리초 단위로 값을 내림한 결과입니다. 또한 floor 연산을 적용한 새로운 DatetimeIndex에는 더 이상 규칙적인 빈도(freq) 정보가 유지되지 않아 freq=None으로 표시됩니다.