[python] 시계열_리샘플링(resample,업샘플링,다운샘플링), 시프팅, 윈도잉
2022. 4. 21. 15:15ㆍ파이썬
리샘플링(resample), 시프팅, 윈도잉
- 시계열 데이터에서 중요한 함수들
리샘플링
- 더 높거나, 낮은 주기로 표본들을 다시 추출(resampling) 하는 것이 중요하다.
- 이에 resample 함수와 asfreq함수를 사용한다
resample
- 기본적으로 데이터를 집계한다
asfreq
- 기본적으로 데이터를 선택한다
업 샘플링
분 단위, 초 단위로 샘플양을 증가시키는 리샘플링
다운샘플링
몇 일, 몇 달 단위로 샘플양을 감소시키는 리샘플링
df_resample = df.resample(rule='Y').sum()
df_resample
- 2015-01-01, 2015-01-02... 2015-12-31 간의 데이터를 전부 더해서 다운 샘플링한다
rule 규칙
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA, BY business year end frequency
AS, YS year start frequency
BAS, BYS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds
데이터를 다운 샘플링 할때 영업일 기준 연말 데이터를 리샘플링 해보자
goog.plot(alpha=0.5,style="-")
goog.resample('BA').mean().plot(style=':')
goog.asfreq('BA').plot(style="--")
plt.legend(['input','resample','asfreq'],loc="upper left")
- resample은 전년도 평균을 보여주고, asfreq는 연말 주가를 보여준다.
시간이동(Time-shift)
Shift(), tshift() 두 메서드가잇다
shift()
- 데이터를 이동시킨다
tshift()
- 인덱스를 이동시킨다.
fig, ax = plt.subplots(3, sharey=True)
# apply a frequency to the data
goog = goog.asfreq('D', method='pad')
goog.plot(ax=ax[0])
goog.shift(900).plot(ax=ax[1])
goog.tshift(900).plot(ax=ax[2])
# legends and annotations
local_max = pd.to_datetime('2007-11-05')
offset = pd.Timedelta(900, 'D')
ax[0].legend(['input'], loc=2)
ax[0].get_xticklabels()[2].set(weight='heavy', color='red')
ax[0].axvline(local_max, alpha=0.3, color='red')
ax[1].legend(['shift(900)'], loc=2)
ax[1].get_xticklabels()[2].set(weight='heavy', color='red')
ax[1].axvline(local_max + offset, alpha=0.3, color='red')
ax[2].legend(['tshift(900)'], loc=2)
ax[2].get_xticklabels()[1].set(weight='heavy', color='red')
ax[2].axvline(local_max + offset, alpha=0.3, color='red');
- shift(900) 은 데이터를 900일 이동시켰고 반대쪽은 NA로 설정한다
- tshift(900)은 인덱스 값을 900일만큼 이동시킨다
goog.head()의 초기 날짜는 2004-08-19인데 tshift(900)을 한 초기 날짜는 2007-02-05가 된다
'파이썬' 카테고리의 다른 글
[Python] 시애틀 자전거 수 시각화 (0) | 2022.04.29 |
---|---|
[Python] Pivot Table (피벗테이블) (0) | 2022.04.26 |
[Python] inplace = True? (0) | 2022.04.21 |
[python] loc, iloc 차이 (0) | 2022.04.07 |
[Python] Dataframe Column Change (0) | 2022.04.07 |