시계열 데이터 다루기

wandajeong·2023년 6월 9일
0

Data Handling

목록 보기
12/15

날짜처리

  • Timestamp
pd.Timestamp(0)              #1970-01-01부터 계산됨
pd.Timestamp(10, unit='D')   #1970-01-11
pd.Timestamp(10, unit='M')
  • to_datetime
pd.to_datetime('2020-05-01')

s=pd.Series([10, 100, 1000, 10000])
pd.to_datetime(s, unit='D')

s=pd.Series(['2015-12-05', '2020-11-08', '2018-13-01'])  #잘못된 날짜형식 
pd.to_datetime(s)   #에러 
pd.to_datetime(s, errors='coerce')   #에러나면 결측치로
pd.to_datetime(s, errors='ignore')   #에러나는건 무시 

pd.to_datetime('2020년 5월 1일', format='%Y년 %m월 %d일')

d='시작일자 : 11월 8일, 2020 시작시간: 09:15 am'
f='시작일자 : %m월 %d일, %Y 시작시간: %I:%M %p'
pd.to_datetime(d, format=f)

birth=pd.to_datetime(df['Birth'], format='%Y-%m-%d %H:%M')
  • 날짜 확인/필터링
birth.dt.date  #YYYY-MM-DD문자열로 추출
birth.dt.year
birth.dt.month
birth.dt.day
birth.dt.time
birth.dt.quarter       #몇 분기인지
birth.dt.day_name()    #몇 요일인지 영어 
birth.dt.day_name('Korean')
birth.dt.weekday       #몇 요일인지 숫자 0~6 (5,6이 주말)
birth.dt.weekday >5    #주말여부 
birth.dt.day_name('Korean').isin(['토요일','일요일'])
birth.dt.isocalendar().week   #몇주차인지 
birth.dt.dayofyear            #연기준 몇일째인지 
birth.dt.days_in_month        #해당월이 몇일이나 있는지 확인 
birth.dt.is_leap_year         #윤년확인 
birth.dt.is_month_end         #말일인지 확인 
birth.dt.is_quater_start      #분기시작일인지 확인 
birth.dt.is_quater_end        #분기마지막일인지 확인 
  • 시간 간격 처리
birth + pd.Timedelta(days=100)
birth - pd.Timedalta(weeks=7)

(pd.to_datetime('2020-05-01') - birth).astype('timedelta64[D]')   #일기준 계산결과 필요
(pd.to_datetime('2020-05-01') - birth).astype('timedelta64[M]')   #월기준 계산결과 필요 
(pd.to_datetime('2020-05-01') - birth).total_seconds() / 3600.0   # 시간 기준 계산 결과 필요

pd.date_range('2020-05-01', periods=7, freq='D')   #하루간격 7개 
pd.date_range('2020-05-01', periods=7, freq='W')   #일주일간격 7개 

# df의 최소, 최대 일자
first_time = train.TIME.sort_values().iloc[1]
last_time = train.TIME.sort_values().iloc[-1]
  • datetime to string
pd.date_range(first_time, period=5, freq='D').strftime('%Y%m%d').tolist()

time-series handling

  • 보간
# 1초 단위로 데이터 보간, 이전 데이터 기준으로 
data.resample('1S').ffill()
# 보간 데이터 복원 
data.loc[data['col1'].diff() != 0, 'col1']

# reindex 방식 
new_idx = pd.date_range(start_date, end_date, freq='H')
df = df.set_index('TIME_STAMP')
df = df.reindex(new_idx)
df = df.interpolate()
  • 시간 기준 groupby
df.resample('1H', origin='start').mean()  # origin 시간을 포함해서 1시간(start = 01:00:00 이라면 01:00:00 ~ 01.59.59 범위 resample)
df.resample('1H', origin='end', closed='right', label='right').mean()
# 마지막 시간을 포함해서 1시간을 집계히고 표기방식은 마지막 시간 
# 마지막 시간이 02:30:00이라면, 01:29:29~02:30:00까지 집계하고 표기는 '02:30:00'
  • 가장 가까운 시간 구하기
idx = (df['TIME'] - pd.Timestamp('2020-10-20 00:00:00')).abs().idxmin()
idx = df['TIME'].sub(pd.Timestamp('2020-10-20 00:00:00')).abs().idxmin()
  • 시계열 데이터 연속기간 구하기
# 평균을 초과하는 값의 가장 긴 연속기간
def longest_period_above_mean(data):
	mean_val = data.mean()
    above_mean = data > mean_val
    consecutive_lengths = above_mean.groupby((above_mean!=above_mean.shift()).cumsum()).apply(lambda x: x[x].size)
    return longest_period 
    
# 최장 연속 감소 기간 
def longest_period_decreasing(data):
	diff = data.diff()  # 차분 
    is_decreasing = diff < 0
    consecutive_decrease = is_decreasing.astype('int').groupby((~is_decreasing).cumsum()).cumsum()
    max_decrease_period = consecutive_decrease.max()
    return max_decrease_period
profile
ML/DL swimmer

0개의 댓글