DateTimeIndex에서 하루 중 특정 시간대 사이에 있는 값들의 인덱스 위치를 반환하려면 DateTimeIndex.indexer_between_time() 메서드를 사용합니다. 이때 시작 시간까지 결과에 포함하려면 include_start 매개변수를 True로 설정하면 됩니다.
1. 필요한 라이브러리 임포트
먼저 pandas 라이브러리를 임포트합니다.
import pandas as pd
2. DatetimeIndex 생성
기간(periods)은 7, 빈도(freq)는 분을 의미하는 '20T'(20분 간격)로 설정하고, 시간대(tz)는 호주 애들레이드(Australia/Adelaide)로 지정하여 DatetimeIndex를 생성합니다.
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')
생성된 DateTimeIndex를 출력해 확인합니다.
print("DateTimeIndex...\n", datetimeindex)3. 특정 시간대 사이의 인덱스 위치 조회
이제 indexer_between_time() 메서드로 특정 시간대 사이의 값들에 대한 인덱스 위치를 조회합니다. start_time은 '03:10:50', end_time은 '03:50:50'으로 설정하고, include_start 매개변수를 True로 지정하여 시작 시간을 결과에 포함시킵니다.
print("\nIndex locations of values between particular time of day...\n",
datetimeindex.indexer_between_time('03:10:50','03:50:50', include_start = True))예제
다음은 위 과정을 모두 포함한 전체 코드입니다.
import pandas as pd
# 기간 7, 빈도는 분(T) 단위인 DatetimeIndex 생성
# 시간대는 Australia/Adelaide로 지정
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')
# DateTimeIndex 출력
print("DateTimeIndex...\n", datetimeindex)
# DateTimeIndex 빈도 출력
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)
# 특정 시각(여기서는 03:10:50)의 값에 대한 인덱스 위치 출력
print("\nIndex locations of values at particular time of day...\n",
datetimeindex.indexer_at_time('2021-10-30 03:10:50'))
# 특정 시간대 사이의 값에 대한 인덱스 위치 출력
# start_time은 '03:10:50', end_time은 '03:50:50'으로 설정
print("\nIndex locations of values between particular time of day...\n",
datetimeindex.indexer_between_time('03:10:50','03:50:50', include_start = True))출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
DateTimeIndex... DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 02:50:50+10:30', '2021-10-30 03:10:50+10:30', '2021-10-30 03:30:50+10:30', '2021-10-30 03:50:50+10:30', '2021-10-30 04:10:50+10:30', '2021-10-30 04:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='20T') DateTimeIndex frequency... <20 * Minutes> Index locations of values at particular time of day... [2] Index locations of values between particular time of day... [2 3 4]
결과 해석
indexer_at_time()은 정확히 일치하는 시각(03:10:50) 하나만 찾아 인덱스 [2]를 반환한 반면, indexer_between_time()은 범위 내의 여러 값을 찾아 [2 3 4]를 반환했습니다. 즉, 03:10:50(include_start=True로 시작 시간 포함), 03:30:50, 03:50:50에 해당하는 세 개의 값이 조건 범위에 포함된 것입니다. 만약 종료 시간까지 포함하고 싶다면 include_end 매개변수를 True로 설정하면 됩니다.