Pandas 시계열 제어 (1)

stav·2024년 6월 6일
0
post-thumbnail

📝 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('2023-06-06 00:00:00')

Timestamp의 사칙연산

  • 설명: Timestamp는 시계열 데이터 간의 덧셈, 뺄셈 연산이 가능하다.
from pandas import Timestamp

# 두 Timestamp의 차이를 구함
timestamp1 = Timestamp('2023-06-06')
timestamp2 = Timestamp('2023-06-10')
difference = timestamp2 - timestamp1
difference
# 결과: Timedelta('4 days 00:00:00')

# Timestamp에 시간 차이를 더함
new_timestamp = timestamp1 + difference
new_timestamp
# 결과: Timestamp('2023-06-10 00:00:00')

DatetimeIndex

  • 정의: 여러 Timestamp 객체를 모아 만든 인덱스 배열로, 시계열 데이터를 다루는 데 사용된다.
  • 생성: pd.DatetimeIndex(['YYYY-MM-DD', 'YYYY-MM-DD']) 형태로 생성할 수 있다.
# 여러 날짜를 인덱스로 갖는 DatetimeIndex 생성
dates = pd.DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03'])
dates
# 결과: DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03'], dtype='datetime64[ns]', freq=None)

DatetimeIndex의 활용 예제

  • 예제: DatetimeIndex를 사용하여 데이터프레임의 인덱스로 활용
# 예제 데이터프레임 생성
data = [10, 20, 30]
df = pd.DataFrame(data, index=dates, columns=['value'])
df
# 결과:
#             value
# 2023-01-01     10
# 2023-01-02     20
# 2023-01-03     30

# DatetimeIndex의 속성 접근
df.index.day
# 결과: Int64Index([1, 2, 3], dtype='int64')

pd.to_datetime()

  • 정의: 문자열이나 다른 형태의 데이터를 Timestamp로 변환하는 함수이다.
  • 파라미터:
    • arg: 변환할 데이터 (문자열, 리스트 등).
    • errors: 에러 처리 방법 ('raise', 'coerce', 'ignore').
    • format: 날짜 형식 문자열.
    • unit: 데이터의 시간 단위 (예: 's', 'ms').
  • 사용 예:
# 문자열 리스트를 Timestamp로 변환
date_strings = ['2023-01-01', '2023-01-02', '2023-01-03']
dates = pd.to_datetime(date_strings)
dates
# 결과: DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03'], dtype='datetime64[ns]', freq=None)

📝 02 시계열 제어 - 날짜 범위 생성(date_range) ✏️


pd.date_range()

  • 정의: 특정 시작일과 종료일 사이의 날짜 범위를 생성하는 함수이다.
  • 파라미터:
    • start: 시작 날짜.
    • end: 종료 날짜.
    • periods: 생성할 날짜의 수.
    • freq: 날짜 생성의 빈도 (예: 'D' - 일간, 'M' - 월간).
  • 사용 예:
# 2023년 1월부터 2023년 12월까지 월간 날짜 생성
date_range = pd.date_range(start='2023-01-01', end='2023-12-31', freq='M')
date_range
# 결과: DatetimeIndex(['2023-01-31', '2023-02-28', '2023-03-31', '2023-04-30',
#                      '2023-05-31', '2023-06-30', '2023-07-31', '2023-08-31',
#                      '2023-09-30', '2023-10-31', '2023-11-30', '2023-12-31'],
#                     dtype='datetime64[ns]', freq='M')
  • 사용 예 2:
# 예제 데이터프레임 생성
data = range(1, 13)
df = pd.DataFrame(data, index=date_range, columns=['value'])
df
# 결과:
#             value
# 2023-01-31      1
# 2023-02-28      2
# 2023-03-31      3
# 2023-04-30      4
# 2023-05-31      5
# 2023-06-30      6
# 2023-07-31      7
# 2023-08-31      8
# 2023-09-30      9
# 2023-10-31     10
# 2023-11-30     11
# 2023-12-31     12

📝 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
# 결과: Period('2023-06', 'M')

pd.PeriodIndex()

  • 정의: 여러 Period 객체를 모아 만든 인덱스 배열로, 특정 기간을 인덱스로 사용한다.
  • 생성: pd.PeriodIndex(['YYYY-MM', 'YYYY-MM']) 형태로 생성할 수 있다.
# 여러 기간을 인덱스로 갖는 PeriodIndex 생성
periods = pd.PeriodIndex(['2023-01', '2023-02', '2023-03'], freq='M')
periods
# 결과: PeriodIndex(['2023-01', '2023-02', '2023-03'], dtype='period[M]')

pd.period_range()

  • 정의: 특정 시작 기간과 종료 기간 사이의 기간 범위를 생성하는 함수이다.
  • 파라미터:
    • start: 시작 기간.
    • end: 종료 기간.
    • periods: 생성할 기간의 수.
    • freq: 기간 생성의 빈도 (예: 'M' - 월간, 'Y' - 연간).
  • 사용 예:
# 2023년 1월부터 2023년 12월까지 월간 기간 생성
period_range = pd.period_range(start='2023-01', end='2023-12', freq='M')
period_range
# 결과: PeriodIndex(['2023-01', '2023-02', '2023-03', '2023-04', '2023-05', '2023-06',
#                    '2023-07', '2023-08', '2023-09', '2023-10', '2023-11', '2023-12'],
#                   dtype='period[M]')

pd.to_period()

  • 정의: Timestamp 객체를 Period 객체로 변환하는 함수이다.
  • 사용 예:
# 날짜 리스트를 기간으로 변환
dates = pd.date_range('2023-01-01', periods=3, freq='M')
periods = dates.to_period()
periods
# 결과: PeriodIndex(['2023-01', '2023-02', '2023-03'], dtype='period[M]')

pd.to_timestamp()

  • 정의: Period 객체를 Timestamp 객체로 변환하는 함수이다.
  • 사용 예:
# 기간 리스트를 Timestamp로 변환
timestamps = periods.to_timestamp()
timestamps
# 결과: DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'], dtype='datetime64[ns]', freq='MS')

📝 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
# 결과: Timedelta('1 days 06:05:01')

pd.TimedeltaIndex()

  • 정의: 여러 Timedelta 객체를 모아 만든 인덱스 배열로, 시간 차이를 인덱스로 사용한다.
  • 생성: pd.TimedeltaIndex(['1 days', '2 days']) 형태로 생성할 수 있다.
# 여러 시간 차이를 인덱스로 갖는 TimedeltaIndex 생성
timedeltas = pd.TimedeltaIndex(['1 days', '2 days', '3 days'])
timedeltas
# 결과: TimedeltaIndex(['1 days 00:00:00', '2 days 00:00:00', '3 days 00:00:00'], dtype='timedelta64[ns]', freq=None)

pd.to_timedelta()

  • 정의: 문자열이나 다른 형태의 데이터를 Timedelta로 변환하는 함수이다.
  • 사용 예:
# 문자열 리스트를 Timedelta로 변환
time_strings = ['1 days', '2 days', '3 days']
timedeltas = pd.to_timedelta(time_strings)
timedeltas
# 결과: TimedeltaIndex(['1 days 00:00:00', '2 days 00:00:00', '3 days 00:00:00'], dtype='timedelta64[ns]', freq=None)

pd.timedelta_range()

  • 정의: 특정 시작 시간 차이와 종료 시간 차이 사이의 시간 차이 범위를 생성하는 함수이다.
  • 파라미터:
    • start: 시작 시간 차이.
    • end: 종료 시간 차이.
    • periods: 생성할 시간 차이의 수.
    • freq: 시간 차이 생성의 빈도 (예: 'D' - 일간, 'H' - 시간간).
  • 사용 예:
# 1일 간격으로 5일간의 시간 차이 생성
timedelta_range = pd.timedelta_range(start='1 days', end='5 days', freq='D')
timedelta_range
# 결과: TimedeltaIndex(['1 days 00:00:00', '2 days 00:00:00', '3 days 00:00:00',
#                      '4 days 00:00:00', '5 days 00:00:00'],
#                     dtype='timedelta64[ns]', freq='D')

📝 05 시계열 제어 - 날짜_시간 속성 접근자(.dt) ✏️

.dt 접근자

  • 정의: DatetimeIndexTimestamp 객체의 날짜와 시간 정보를 추출할 수 있는 속성 접근자이다.
  • 사용 예:
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})

# .dt 접근자를 사용하여 연도 추출
df['year'] = df['date'].dt.year
df
# 결과:
#         date  year
# 0 2023-01-01  2023
# 1 2023-02-01  2023
# 2 2023-03-01  2023

# .dt 접근자를 사용하여 월 추출
df['month'] = df['date'].dt.month
df
# 결과:
#         date  year  month
# 0 2023-01-01  2023      1
# 1 2023-02-01  2023      2
# 2 2023-03-01  2023      3

# .dt 접근자를 사용하여 일(day) 추출
df['day'] = df['date'].dt.day
df
# 결과:
#         date  year  month  day
# 0 2023-01-01  2023      1    1
# 1 2023-02-01  2023      2    1
# 2 2023-03-01  2023      3    1

.dt 접근자를 사용한 다양한 속성 추출

  • 예제: .dt 접근자를 사용하여 시간, 분, 초 등의 다양한 날짜 및 시간 정보를 추출할 수 있다.
# .dt 접근자를 사용하여 시간(hour) 추출
df['hour'] = df['date'].dt.hour
df
# 결과:
#         date  year  month  day  hour
# 0 2023-01-01  2023      1    1     0
# 1 2023-02-01  2023      2    1     0
# 2 2023-03-01  2023      3    1     0

# .dt 접근자를 사용하여 분(minute) 추출
df['minute'] = df['date'].dt.minute
df
# 결과:
#         date  year  month  day  hour  minute
# 0 2023-01-01  2023      1    1     0       0
# 1 2023-02-01  2023      2    1     0       0
# 2 2023-03-01  2023      3    1     0       0

# .dt 접근자를 사용하여 초(second) 추출
df['second'] = df['date'].dt.second
df
# 결과:
#         date  year  month  day  hour  minute  second
# 0 2023-01-01  2023      1    1     0       0       0
# 1 2023-02-01  2023      2    1     0       0       0
# 2 2023-03-01  2023      3    1     0       0       0

📝 06 시계열 제어 - Timestamp와 DatetimeIndex의 메소드와 속성(+한국 locale 포맷) ✏️

Timestamp와 DatetimeIndex의 메소드와 속성

  • 설명: TimestampDatetimeIndex 객체는 다양한 메소드와 속성을 제공하여 날짜와 시간을 다룰 수 있다.

Timestamp 객체의 메소드와 속성

  • 예제: Timestamp 객체의 다양한 속성에 접근하는 방법
import pandas as pd

# Timestamp 객체 생성
timestamp = pd.Timestamp('2023-06-06 12:34:56')

# 다양한 속성 접근
year = timestamp.year   # 결과: 2023
month = timestamp.month # 결과: 6
day = timestamp.day     # 결과: 6

DatetimeIndex 객체의 메소드와 속성

  • 예제: DatetimeIndex 객체의 다양한 속성에 접근하는 방법
# DatetimeIndex 객체 생성
dates = pd.date_range('2023-01-01', periods=3, freq='D')

# 다양한 속성 접근
years = dates.year      # 결과: Int64Index([2023, 2023, 2023], dtype='int64')
months = dates.month    # 결과: Int64Index([1, 1, 1], dtype='int64')
days = dates.day        # 결과: Int64Index([1, 2, 3], dtype='int64')

한국 로케일 포맷

  • 설명: 날짜와 시간을 한국어로 포맷할 수 있다.
# 한국 로케일 설정
import locale
locale.setlocale(locale.LC_TIME, 'ko_KR.UTF-8')

# Timestamp 객체의 날짜를 한국어로 포맷
timestamp = pd.Timestamp('2023-06-06')
formatted_date = timestamp.strftime('%Y년 %m월 %d일 %A')
formatted_date
# 결과: '2023년 06월 06일 화요일'

profile
Data Analyst Challenge

0개의 댓글

관련 채용 정보