Pandas의 DateTimeIndex에 대해 초(second) 단위 빈도로 내림(floor) 연산을 수행하려면 DateTimeIndex.floor() 메서드를 사용하면 됩니다. 이때 freq 매개변수에 초를 의미하는 'S' 값을 지정해 주면 됩니다.
floor 연산은 타임스탬프의 나노초 등 세부 단위를 잘라내어 지정한 빈도 단위로 값을 내림 처리할 때 유용하게 사용됩니다.
1단계: 필요한 라이브러리 임포트
먼저 pandas 라이브러리를 임포트합니다.
import pandas as pd
2단계: DatetimeIndex 생성
시작 시점을 '2021-10-18 07:20:32.261811624'로 하고, 주기(periods)는 5개, 빈도(freq)는 '40S'(40초 간격), 시간대(tz)는 호주 애들레이드(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 연산 수행
이제 DateTimeIndex의 각 타임스탬프에 대해 초 빈도('S')로 내림 연산을 수행합니다. 나노초 단위의 소수점 이하 값이 잘려나가고 초 단위까지의 값으로 정렬되는 것을 확인할 수 있습니다.
print("\nPerforming floor operation with seconds frequency...\n",
datetimeindex.floor(freq='S'))
전체 예제 코드
지금까지 설명한 내용을 하나로 합친 전체 코드는 다음과 같습니다.
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의 빈도 출력
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# 초(second) 값 추출
res = datetimeindex.second
# 초 값만 출력
print("\nThe seconds from DateTimeIndex...\n", res)
# 초 빈도('S')로 floor(내림) 연산 수행
print("\nPerforming floor operation with seconds frequency...\n",
datetimeindex.floor(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 seconds from DateTimeIndex... Int64Index([32, 12, 52, 32, 12], dtype='int64') Performing floor operation with seconds frequency... DatetimeIndex(['2021-10-18 07:20:32+10:30', '2021-10-18 07:21:12+10:30', '2021-10-18 07:21:52+10:30', '2021-10-18 07:22:32+10:30', '2021-10-18 07:23:12+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq=None)
결과를 보면 원래 나노초 소수점(.261811624)을 포함하고 있던 타임스탬프들이 floor(freq='S') 연산 후 초 단위까지의 깔끔한 값으로 내림 처리된 것을 확인할 수 있습니다.