0Pricing
Pandas & NumPy Academy · 강의

시계열 리샘플링

resample('ME').sum()으로 일별 데이터를 월별로 다운샘플링하고 앞의 값으로 채워 누락된 구간을 보완합니다.

시계열 리샘플링은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is Resampling?

Resampling changes the frequency of a time series. Downsampling reduces frequency — for example, converting daily data to monthly totals. Upsampling increases frequency — for example, converting monthly data to daily, filling gaps with interpolated values. Both operations require a DatetimeIndex and are performed with the resample() method, which is Pandas' time-aware version of groupby().

The resample() Method

df.resample(rule) creates a DatetimeIndexResampler object, where rule is a frequency offset alias. Like groupby(), nothing is computed until you chain an aggregation method. Common rules: 'D' (day), 'W' (week), 'ME' (month end), 'QE' (quarter end), 'YE' (year end). The DataFrame must have a DatetimeIndex.

import pandas as pd
import numpy as np

np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=90, freq='D')
df = pd.DataFrame({'sales': np.random.randint(100, 500, 90)}, index=dates)

print(df.head())
print('Shape:', df.shape)  # (90, 1) -- 90 daily rows

Downsampling: Daily to Monthly

To downsample daily data to monthly, call resample('ME') and chain an aggregation. sum() gives monthly totals; mean() gives monthly averages; last() gives the last value in each period. The result has one row per period, with the period-end date as the index label.

# Monthly totals
monthly_sum = df.resample('ME').sum()
print(monthly_sum)
# sales
# 2024-01-31    9876
# 2024-02-29    8765
# 2024-03-31    9234

# Monthly averages
monthly_mean = df.resample('ME').mean().round(1)
print(monthly_mean)

Downsampling to Weekly

Resample with 'W' to aggregate by calendar week ending on Sunday. Use 'W-MON' if you want weeks ending on Monday. Pandas groups all dates within each week together and applies the aggregation. This is useful for weekly reporting where you want one summary row per week.

# Weekly sum
weekly = df.resample('W').sum()
print(weekly.head())
# sales
# 2024-01-07    2010  <- Jan 1-7
# 2024-01-14    2340  <- Jan 8-14
# ...

# Weekly max and count using agg()
weekly_stats = df.resample('W').agg(['sum', 'mean', 'max'])
print(weekly_stats.head())

Applying Multiple Aggregations

Just like groupby(), you can chain .agg() on a resampler to compute multiple statistics in a single pass. Pass a list of function names or a dict for named aggregations. This is the most efficient way to build a comprehensive time-series summary table.

monthly_stats = df.resample('ME').agg(
    total_sales=('sales', 'sum'),
    avg_sales=('sales', 'mean'),
    peak_sales=('sales', 'max'),
    days_counted=('sales', 'count')
)
print(monthly_stats.round(1))
#             total_sales  avg_sales  peak_sales  days_counted
# 2024-01-31         9876      318.6         499            31

OHLC Resampling for Financial Data

For financial time series, the .ohlc() method resamples to Open, High, Low, Close (OHLC) values per period — the standard candlestick representation. This is only meaningful for numeric data representing a price or level. Each column in the input gets four OHLC columns in the output.

# OHLC monthly resampling
ohlc = df['sales'].resample('ME').ohlc()
print(ohlc)
#             open  high   low  close
# 2024-01-31   365   499   101    243
# 2024-02-29   ...

Upsampling: Monthly to Daily

Upsampling increases frequency, which creates rows for timestamps that did not exist in the original data. These new rows initially contain NaN. You then fill them with a method that makes sense for your data: ffill() (forward fill — carry the last known value forward) or bfill() (backward fill — use the next known value), or interpolate() for smooth interpolation.

# Monthly data
monthly = pd.Series(
    [100, 120, 115],
    index=pd.date_range('2024-01-31', periods=3, freq='ME')
)
print(monthly)

# Upsample to daily (creates NaN rows)
daily = monthly.resample('D').asfreq()
print(daily.head(10))
# 2024-01-31    100.0
# 2024-02-01      NaN  <- new row
# ...

Filling Upsampled Gaps

After upsampling, fill the NaN gaps created for new timestamps. ffill() propagates the last known value forward until the next real observation — good for prices where the last traded price remains valid. interpolate(method='linear') fills with linearly spaced values between observations — good for smooth continuous variables.

# Forward fill: carry monthly value forward to every day
daily_ffill = monthly.resample('D').ffill()
print(daily_ffill.head(35))
# 2024-01-31    100
# 2024-02-01    100  <- forward filled
# ...
# 2024-02-29    120  <- new month value

# Linear interpolation
daily_interp = monthly.resample('D').interpolate(method='linear')
print(daily_interp.head(10))

Resampling Within Groups

You can combine groupby() and resample() to resample within each group separately. Call groupby(column).resample(rule) on a DataFrame with a DatetimeIndex. This produces a result with a MultiIndex where the outer level is the group key and the inner level is the resampled time period — very useful for product-level or region-level time series analysis.

df2 = pd.DataFrame({
    'product': ['A', 'B', 'A', 'B', 'A', 'B'],
    'sales': [100, 150, 120, 130, 110, 160]
}, index=pd.date_range('2024-01-01', periods=6, freq='ME'))

# Monthly sum per product
result = df2.groupby('product').resample('QE').sum()
print(result)

Custom Offset Anchoring

By default, 'ME' anchors to calendar month-end dates. For non-standard fiscal periods, use offsets like 'QS-APR' (quarter starting April) or 'YS-OCT' (year starting October). Pandas supports many anchored offset aliases. Check the Pandas documentation for the full list when working with non-calendar fiscal periods.

# Fiscal year starting in April
fiscal_annual = df.resample('YE-MAR').sum()
print(fiscal_annual)
# sales
# 2024-03-31    XXXX  <- April 2023 to March 2024

# Quarter starting in April
fiscal_q = df.resample('QE-MAR').mean().round(0)
print(fiscal_q)

Checking Resampled Result Integrity

After resampling, always verify the result makes sense. Check that the number of output periods matches expectations, that no periods are missing (look for NaN in the output), and that the sum of monthly totals equals the sum of the original daily data when downsampling with sum(). These sanity checks catch off-by-one errors in frequency strings and missing date ranges.

monthly = df.resample('ME').sum()

# Verify: monthly totals should sum to daily total
assert monthly['sales'].sum() == df['sales'].sum(), 'Sum mismatch!'

# Verify: expected number of months
print('Months:', len(monthly))  # should be 3 for 90 days Jan-Mar

# Check for any NaN
print('NaN count:', monthly.isna().sum().sum())

Quick Check

Test your understanding of resampling time series from this lesson.

Lesson Recap

In this lesson you learned: resample() is the time-aware equivalent of groupby() for changing time series frequency; downsampling aggregates data (daily to monthly with sum/mean); upsampling creates new timestamps that must be filled with ffill() or interpolate(); and you can combine groupby() with resample() for group-level time aggregation. Next up we explore shifting and lag features.

자주 묻는 질문

“시계열 리샘플링” 강의는 무료인가요?

네 — “시계열 리샘플링” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“시계열 리샘플링”에서 뭘 배우나요?

resample('ME').sum()으로 일별 데이터를 월별로 다운샘플링하고 앞의 값으로 채워 누락된 구간을 보완합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“시계열 리샘플링” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. DatetimeIndex와 기간 범위
  2. 시계열 리샘플링
  3. 시프트와 지연 특성
  4. 시간 특성 추출하기
← Pandas & NumPy Academy(으)로 돌아가기