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

Python Pandas – DateTimeIndex.normalize()로 시간을 자정(00:00:00)으로 변환하는 방법

Pandas에서 DateTimeIndex.normalize() 메서드를 사용하면 DateTimeIndex에 포함된 시간 성분을 자정(00:00:00)으로 손쉽게 변환할 수 있습니다. 이 메서드는 날짜 정보는 그대로 유지하면서 시·분·초 부분만 잘라내기 때문에, 일 단위로 데이터를 그룹화하거나 집계할 때 매우 유용합니다.

1. 필요한 라이브러리 임포트

먼저 pandas를 임포트합니다.

import pandas as pd

2. DatetimeIndex 생성

시작 시점을 '2021-10-30 02:30:50'으로 지정하고, 주기(periods)는 7개, 빈도(freq)는 10시간('10H'), 시간대(tz)는 'Australia/Adelaide'로 설정하여 DatetimeIndex를 생성합니다.

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

3. 생성된 DateTimeIndex 확인

생성된 DateTimeIndex를 출력해 내용을 확인해 보겠습니다.

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

4. normalize()로 시간을 자정으로 변환

normalize()를 호출하면 각 날짜의 시간 성분이 모두 자정(00:00:00)으로 변환됩니다.

print("\nNormalize (converted the time component to midnight)...\n", datetimeindex.normalize())

전체 예제 코드

지금까지의 과정을 하나의 코드로 정리하면 다음과 같습니다.

import pandas as pd

# 주기 7, 빈도 10H(10시간), 시간대 Australia/Adelaide로 DatetimeIndex 생성
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

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

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

# 시간 성분을 자정(00:00:00)으로 변환
print("\nNormalize (converted the time component to midnight)...\n", datetimeindex.normalize())

실행 결과

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

DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 12:30:50+10:30',
'2021-10-30 22:30:50+10:30', '2021-10-31 08:30:50+10:30',
'2021-10-31 18:30:50+10:30', '2021-11-01 04:30:50+10:30',
'2021-11-01 14:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='10H')
DateTimeIndex frequency...
<10 * Hours>

Normalize (converted the time component to midnight)...
DatetimeIndex(['2021-10-30 00:00:00+10:30', '2021-10-30 00:00:00+10:30',
'2021-10-30 00:00:00+10:30', '2021-10-31 00:00:00+10:30',
'2021-10-31 00:00:00+10:30', '2021-11-01 00:00:00+10:30',
'2021-11-01 00:00:00+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

정리

출력 결과를 보면 원래 인덱스에는 '02:30:50', '12:30:50' 등 다양한 시각이 포함되어 있었지만, normalize() 적용 후에는 모든 항목이 해당 날짜의 00:00:00으로 통일된 것을 확인할 수 있습니다. 한 가지 주의할 점은 normalize()를 적용한 결과 인덱스의 freq 속성이 None으로 변경된다는 것입니다. 따라서 이후 빈도 기반 연산이 필요하다면 별도로 빈도를 다시 지정해야 할 수 있습니다.