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

Python Pandas – DateTimeIndex에서 분(Minute) 값 추출하는 방법

Python의 Pandas 라이브러리에서 특정 시계열 빈도로 생성된 DateTimeIndex에서 '분(minute)' 값을 추출하려면 DateTimeIndex.minute 속성을 사용하면 됩니다. 이 속성은 인덱스에 포함된 각 타임스탬프의 분 정보를 정수형 배열(Int64Index) 형태로 반환합니다.

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

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

import pandas as pd

2. DatetimeIndex 생성

시작 시점을 '2021-10-20 02:30:55'로 지정하고, 총 6개의 구간(periods=6)을 만들되 빈도는 'T', 즉 분(minute) 단위로 설정합니다. 또한 시간대(timezone)는 호주 시드니(Australia/Sydney)로 지정합니다.

datetimeindex = pd.date_range('2021-10-20 02:30:55', periods=6, tz='Australia/Sydney', freq='T')

3. DateTimeIndex 출력 및 분 추출

생성된 DateTimeIndex를 화면에 출력해 내용을 확인합니다.

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

그다음 minute 속성을 사용해 각 타임스탬프에서 분 값을 가져옵니다.

print("\nGetting the minute..\n", datetimeindex.minute)

전체 예제 코드

import pandas as pd

# periods=6, 빈도는 'T' 즉 분(minute) 단위로 DatetimeIndex 생성
# 시간대는 호주 시드니(Australia/Sydney)
datetimeindex = pd.date_range('2021-10-20 02:30:55', periods=6, tz='Australia/Sydney', freq='T')

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

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

# 분(minute) 값 추출
print("\nGetting the minute..\n", datetimeindex.minute)

실행 결과

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:55+11:00', '2021-10-20 02:31:55+11:00',
'2021-10-20 02:32:55+11:00', '2021-10-20 02:33:55+11:00',
'2021-10-20 02:34:55+11:00', '2021-10-20 02:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='T')
DateTimeIndex frequency...
<Minute>

Getting the minute..
Int64Index([30, 31, 32, 33, 34, 35], dtype='int64')

결과 해석

실행 결과를 보면 시작 시각이 02:30:55이고 빈도가 1분이므로, 인덱스에는 02:30부터 02:35까지 6개의 타임스탬프가 순차적으로 생성됩니다. 마지막 줄의 Int64Index([30, 31, 32, 33, 34, 35])는 각 타임스탬프에서 추출한 분 값입니다.

참고: 최신 버전의 pandas(2.2 이상)에서는 빈도 별칭 'T'가 deprecated 되었으므로, 대신 'min'을 사용하는 것이 권장됩니다. 예를 들어 freq='min'과 같이 작성하면 동일한 결과를 얻을 수 있습니다.