📝 01 시계열 제어 - 날짜와 시간(Timestamp, DatetimeIndex, to_datetime) ✏️
pd.Timestamp()
- 정의:
Timestamp
는 특정 시점의 날짜와 시간을 나타내는 데이터 타입이다.
- 생성:
pd.Timestamp('YYYY-MM-DD')
형태로 생성할 수 있다.
import pandas as pd
timestamp = pd.Timestamp('2023-06-06')
timestamp
Timestamp의 사칙연산
- 설명:
Timestamp
는 시계열 데이터 간의 덧셈, 뺄셈 연산이 가능하다.
from pandas import Timestamp
timestamp1 = Timestamp('2023-06-06')
timestamp2 = Timestamp('2023-06-10')
difference = timestamp2 - timestamp1
difference
new_timestamp = timestamp1 + difference
new_timestamp
DatetimeIndex
- 정의: 여러
Timestamp
객체를 모아 만든 인덱스 배열로, 시계열 데이터를 다루는 데 사용된다.
- 생성:
pd.DatetimeIndex(['YYYY-MM-DD', 'YYYY-MM-DD'])
형태로 생성할 수 있다.
dates = pd.DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03'])
dates
DatetimeIndex의 활용 예제
- 예제: DatetimeIndex를 사용하여 데이터프레임의 인덱스로 활용
data = [10, 20, 30]
df = pd.DataFrame(data, index=dates, columns=['value'])
df
df.index.day
pd.to_datetime()
- 정의: 문자열이나 다른 형태의 데이터를
Timestamp
로 변환하는 함수이다.
- 파라미터:
arg
: 변환할 데이터 (문자열, 리스트 등).
errors
: 에러 처리 방법 ('raise', 'coerce', 'ignore').
format
: 날짜 형식 문자열.
unit
: 데이터의 시간 단위 (예: 's', 'ms').
- 사용 예:
date_strings = ['2023-01-01', '2023-01-02', '2023-01-03']
dates = pd.to_datetime(date_strings)
dates
📝 02 시계열 제어 - 날짜 범위 생성(date_range) ✏️
pd.date_range()
- 정의: 특정 시작일과 종료일 사이의 날짜 범위를 생성하는 함수이다.
- 파라미터:
start
: 시작 날짜.
end
: 종료 날짜.
periods
: 생성할 날짜의 수.
freq
: 날짜 생성의 빈도 (예: 'D' - 일간, 'M' - 월간).
- 사용 예:
date_range = pd.date_range(start='2023-01-01', end='2023-12-31', freq='M')
date_range
data = range(1, 13)
df = pd.DataFrame(data, index=date_range, columns=['value'])
df
📝 03 시계열 제어 - 기간과 기간 인덱스(Period, PeriodIndex, period_range, to_period, to_timestamp)
pd.Period()
- 정의: 특정 기간(예: 한 달, 한 해 등)을 나타내는 데이터 타입이다.
- 생성:
pd.Period('YYYY-MM', freq='M')
형태로 생성할 수 있다.
period = pd.Period('2023-06', freq='M')
period
pd.PeriodIndex()
- 정의: 여러
Period
객체를 모아 만든 인덱스 배열로, 특정 기간을 인덱스로 사용한다.
- 생성:
pd.PeriodIndex(['YYYY-MM', 'YYYY-MM'])
형태로 생성할 수 있다.
periods = pd.PeriodIndex(['2023-01', '2023-02', '2023-03'], freq='M')
periods
pd.period_range()
- 정의: 특정 시작 기간과 종료 기간 사이의 기간 범위를 생성하는 함수이다.
- 파라미터:
start
: 시작 기간.
end
: 종료 기간.
periods
: 생성할 기간의 수.
freq
: 기간 생성의 빈도 (예: 'M' - 월간, 'Y' - 연간).
- 사용 예:
period_range = pd.period_range(start='2023-01', end='2023-12', freq='M')
period_range
pd.to_period()
- 정의:
Timestamp
객체를 Period
객체로 변환하는 함수이다.
- 사용 예:
dates = pd.date_range('2023-01-01', periods=3, freq='M')
periods = dates.to_period()
periods
pd.to_timestamp()
- 정의:
Period
객체를 Timestamp
객체로 변환하는 함수이다.
- 사용 예:
timestamps = periods.to_timestamp()
timestamps
📝 04 시계열 제어 - 간격과 간격 인덱스(Timedelta, TimedeltaIndex, to_timedelta, timedelta_range)
pd.Timedelta()
- 정의: 두 시점 사이의 시간 차이를 나타내는 데이터 타입이다.
- 생성:
pd.Timedelta('1 days 06:05:01')
형태로 생성할 수 있다.
timedelta = pd.Timedelta('1 days 06:05:01')
timedelta
pd.TimedeltaIndex()
- 정의: 여러
Timedelta
객체를 모아 만든 인덱스 배열로, 시간 차이를 인덱스로 사용한다.
- 생성:
pd.TimedeltaIndex(['1 days', '2 days'])
형태로 생성할 수 있다.
timedeltas = pd.TimedeltaIndex(['1 days', '2 days', '3 days'])
timedeltas
pd.to_timedelta()
- 정의: 문자열이나 다른 형태의 데이터를
Timedelta
로 변환하는 함수이다.
- 사용 예:
time_strings = ['1 days', '2 days', '3 days']
timedeltas = pd.to_timedelta(time_strings)
timedeltas
pd.timedelta_range()
- 정의: 특정 시작 시간 차이와 종료 시간 차이 사이의 시간 차이 범위를 생성하는 함수이다.
- 파라미터:
start
: 시작 시간 차이.
end
: 종료 시간 차이.
periods
: 생성할 시간 차이의 수.
freq
: 시간 차이 생성의 빈도 (예: 'D' - 일간, 'H' - 시간간).
- 사용 예:
timedelta_range = pd.timedelta_range(start='1 days', end='5 days', freq='D')
timedelta_range
📝 05 시계열 제어 - 날짜_시간 속성 접근자(.dt) ✏️
.dt 접근자
- 정의:
DatetimeIndex
나 Timestamp
객체의 날짜와 시간 정보를 추출할 수 있는 속성 접근자이다.
- 사용 예:
import pandas as pd
date_strings = ['2023-01-01', '2023-02-01', '2023-03-01']
dates = pd.to_datetime(date_strings)
df = pd.DataFrame({'date': dates})
df['year'] = df['date'].dt.year
df
df['month'] = df['date'].dt.month
df
df['day'] = df['date'].dt.day
df
.dt 접근자를 사용한 다양한 속성 추출
- 예제: .dt 접근자를 사용하여 시간, 분, 초 등의 다양한 날짜 및 시간 정보를 추출할 수 있다.
df['hour'] = df['date'].dt.hour
df
df['minute'] = df['date'].dt.minute
df
df['second'] = df['date'].dt.second
df
📝 06 시계열 제어 - Timestamp와 DatetimeIndex의 메소드와 속성(+한국 locale 포맷) ✏️
Timestamp와 DatetimeIndex의 메소드와 속성
- 설명:
Timestamp
와 DatetimeIndex
객체는 다양한 메소드와 속성을 제공하여 날짜와 시간을 다룰 수 있다.
Timestamp 객체의 메소드와 속성
- 예제: Timestamp 객체의 다양한 속성에 접근하는 방법
import pandas as pd
timestamp = pd.Timestamp('2023-06-06 12:34:56')
year = timestamp.year
month = timestamp.month
day = timestamp.day
DatetimeIndex 객체의 메소드와 속성
- 예제: DatetimeIndex 객체의 다양한 속성에 접근하는 방법
dates = pd.date_range('2023-01-01', periods=3, freq='D')
years = dates.year
months = dates.month
days = dates.day
한국 로케일 포맷
- 설명: 날짜와 시간을 한국어로 포맷할 수 있다.
import locale
locale.setlocale(locale.LC_TIME, 'ko_KR.UTF-8')
timestamp = pd.Timestamp('2023-06-06')
formatted_date = timestamp.strftime('%Y년 %m월 %d일 %A')
formatted_date