데이터 분석을 위한 Pandas: 9. 시간 데이터 처리

Pandas는 시간 데이터를 효과적으로 다룰 수 있는 강력한 기능을 제공합니다. 시계열 데이터 분석, 날짜 범위 생성, 시간대 변환 등 다양한 작업을 수행할 수 있습니다


 시간 데이터 생성


# python

import pandas as pd

import numpy as np


# 날짜 범위 생성

dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D')


# 특정 기간 동안의 날짜 생성

dates_month = pd.date_range(start='2023-01-01', periods=30, freq='D')


# 시계열 데이터 생성

ts = pd.Series(np.random.randn(len(dates)), index=dates)

#


 시간 데이터 파싱


# python

# 문자열을 datetime으로 변환

dates = pd.to_datetime(['2023-01-01', '2023-02-15', '2023-03-30'])


# 다양한 형식의 날짜 파싱

dates = pd.to_datetime(['01/01/2023', '15-Feb-2023', '2023.03.30'], format='mixed')

#


 시간 데이터 속성 접근


# python

df = pd.DataFrame({'date': pd.date_range(start='2023-01-01', periods=5)})


print(df['date'].dt.year)

print(df['date'].dt.month)

print(df['date'].dt.day)

print(df['date'].dt.dayofweek)

print(df['date'].dt.quarter)

#


 시간 데이터 연산


# python

# 날짜 더하기/빼기

df['next_week'] = df['date'] + pd.Timedelta(days=7)

df['last_month'] = df['date'] - pd.DateOffset(months=1)


# 두 날짜 사이의 차이

df['days_diff'] = (df['next_week'] - df['date']).dt.days

#


 시간 데이터 리샘플링


# python

ts = pd.Series(np.random.randn(1000), index=pd.date_range('2023-01-01', periods=1000, freq='D'))


# 월별 평균

monthly_mean = ts.resample('M').mean()


# 주별 합계

weekly_sum = ts.resample('W').sum()

#


 시간대 처리


# python

from pytz import timezone


# 시간대 설정

df['date_utc'] = df['date'].dt.tz_localize('UTC')


# 시간대 변환

df['date_kst'] = df['date_utc'].dt.tz_convert('Asia/Seoul')

#


 시계열 데이터 이동 및 변화율 계산


# python

# 이동 평균

ts_rolling = ts.rolling(window=7).mean()


# 변화율 계산

ts_pct_change = ts.pct_change()

#


 기간 데이터 처리


# python

# 기간 생성

periods = pd.period_range('2023-01', periods=12, freq='M')


# 기간 데이터프레임 생성

df_periods = pd.DataFrame({'period': periods, 'value': np.random.randn(12)})


# 기간 데이터 연산

df_periods['next_period'] = df_periods['period'] + 1

#


 시간 기반 인덱싱 및 슬라이싱


# python

# 특정 날짜 데이터 선택

print(ts['2023-06-01'])


# 날짜 범위 선택

print(ts['2023-06-01':'2023-06-30'])


# 특정 연도의 데이터 선택

print(ts['2023'])

#


이러한 시간 데이터 처리 기능을 활용하면 시계열 분석, 금융 데이터 처리, 로그 분석 등 다양한 분야에서 효과적으로 데이터를 다룰 수 있습니다. Pandas의 시간 데이터 처리 기능은 복잡한 시계열 데이터를 쉽게 다룰 수 있게 해주며, 데이터 분석 작업을 크게 간소화합니다.




#파이썬 #Python #데이터분석 #dataanalysis #시간데이터처리 #pandas #time-series #datetime #date-operations #시계열

0 댓글