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

Python Pandas – 인덱스를 무시하고 DateTimeIndex에서 DataFrame 만들기

Pandas에서 DateTimeIndex를 DataFrame으로 변환할 때 기존 인덱스를 무시하고 싶다면 to_frame() 메서드에 index=False 매개변수를 설정하면 됩니다. 이 경우 반환되는 DataFrame에는 원래의 날짜·시간 인덱스가 설정되지 않고, 대신 0부터 시작하는 기본 정수 인덱스가 자동으로 부여됩니다.

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

먼저 필요한 라이브러리를 임포트합니다.

import pandas as pd

2단계: DatetimeIndex 생성하기

기간(periods)은 5개, 빈도(frequency)는 초 단위 'S'로 지정하여 DatetimeIndex를 생성합니다. 여기서는 40초 간격(freq='40S')을 사용했으며, 시간대(timezone)는 Australia/Adelaide로 설정했습니다.

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단계: 인덱스 없이 DataFrame으로 변환하기

to_frame(index=False)를 호출하면 원래의 DateTimeIndex가 반환되는 DataFrame의 인덱스로 설정되지 않습니다. 즉, 날짜·시간 값은 일반 데이터 열로 들어가고, 인덱스는 기본 정수 값(0, 1, 2, ...)으로 채워집니다.

print("\nDateTimeIndex to DataFrame...\n", datetimeindex.to_frame(index=False))

전체 예제 코드

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

import pandas as pd

# periods=5, frequency=S(초 단위), 40초 간격의 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의 빈도(frequency) 출력
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# DateTimeIndex를 DataFrame으로 변환
# index=False를 사용하여 원래 인덱스를 설정하지 않음
print("\nDateTimeIndex to DataFrame...\n", datetimeindex.to_frame(index=False))

실행 결과

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

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>

DateTimeIndex to DataFrame...
0
0 2021-10-18 07:20:32.261811624+10:30
1 2021-10-18 07:21:12.261811624+10:30
2 2021-10-18 07:21:52.261811624+10:30
3 2021-10-18 07:22:32.261811624+10:30
4 2021-10-18 07:23:12.261811624+10:30

결과 해석

출력 결과를 보면 DateTimeIndex의 각 요소가 40초씩 증가하며, 시간대 정보(+10:30)가 함께 표시되는 것을 확인할 수 있습니다. 또한 to_frame(index=False) 덕분에 최종 DataFrame의 인덱스가 날짜·시간 값이 아닌 0부터 4까지의 기본 정수 인덱스로 설정된 점에 주목하세요. 만약 index=True(기본값)를 사용했다면 DateTimeIndex 값 자체가 DataFrame의 인덱스로 지정됩니다.