시작하기무료로 시작하기

이동 평균 표시하기

시계열 값의 이동 평균을 시각화할 수도 있어요. 이는 데이터를 “평활화(smoothing)”하는 것과 같으며, 시계열에 노이즈나 이상치가 많을 때 특히 유용해요. DataFrame df에 대해 다음 명령으로 시계열의 이동 평균을 구할 수 있어요:

df_mean = df.rolling(window=12).mean()

window 매개변수는 시계열의 시간 해상도에 맞춰 설정해야 해요. 예를 들어 일별 데이터에서 1년 단위의 이동 값을 구하려면 window=365로 지정해야 해요. 또한 표준편차(.std())나 분산(.var())과 같은 다른 지표의 이동 값도 쉽게 구할 수 있어요.

이 연습은 강의의 일부입니다

Python으로 시계열 데이터 시각화

강의 보기

연습 안내

  • co2_levels의 52주 이동 평균을 계산해 ma에 할당하세요.
  • co2_levels의 52주 이동 표준편차를 계산해 mstd에 할당하세요.
  • 시계열의 상한을 이동 평균 + (2 * 이동 표준편차)로 정의해 ma[upper]에 할당하세요. 같은 방식으로 하한은 이동 평균 - (2 * 이동 표준편차)로 계산해 ma[lower]에 할당하세요.
  • ma의 꺾은선 그래프를 그리세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Compute the 52 weeks rolling mean of the co2_levels DataFrame
ma = ____.rolling(window=____).____()

# Compute the 52 weeks rolling standard deviation of the co2_levels DataFrame
mstd = ____

# Add the upper bound column to the ma DataFrame
ma['upper'] = ma['co2'] + (____ * ____)

# Add the lower bound column to the ma DataFrame
ma['lower'] = ma['co2'] - (____ * ____)

# Plot the content of the ma DataFrame
ax = ____(linewidth=0.8, fontsize=6)

# Specify labels, legend, and show the plot
ax.set_xlabel('Date', fontsize=10)
ax.set_ylabel('CO2 levels in Mauai Hawaii', fontsize=10)
ax.set_title('Rolling mean and variance of CO2 levels\nin Mauai Hawaii from 1958 to 2001', fontsize=10)
plt.show()
코드 편집 및 실행