리샘플링
리샘플링 (Resampling)
시계열을 다른 주파수로 바꾸는 작업을 리샘플링(resampling)이라고 해요. 데이터를 더 높은 주파수로 옮기는 업샘플링(upsampling), 더 낮은 주파수로 옮기는 다운샘플링(downsampling), 그리고 이 둘의 조합으로 나눌 수 있는데, 이 섹션에서는 각각의 의미와 실제 사용법을 살펴볼게요.
출처: 공식문서
리샘플링은 다음 중 하나로 수행할 수 있어요:
- 업샘플링 (upsampling) - 데이터를 더 높은 주파수로 이동
- 다운샘플링 (downsampling) - 데이터를 더 낮은 주파수로 이동
- 이 둘의 조합. 예: 먼저 업샘플링한 다음 다운샘플링
더 낮은 주파수로 다운샘플링 (Downsampling to a lower frequency)
Polars는 다운샘플링을 group_by 연산의 특수한 경우로 봅니다. 그래서 group_by_dynamic과 group_by_rolling로 수행할 수 있어요 — 시간 기반 그룹 바이 페이지의 예시를 참고하세요.
더 높은 주파수로 업샘플링 (Upsampling to a higher frequency)
30분 간격으로 데이터를 생성하는 예시를 따라가 볼게요:
from datetime import datetime
import polars as pl
df = pl.DataFrame(
{
"time": pl.datetime_range(
start=datetime(2021, 12, 16),
end=datetime(2021, 12, 16, 3),
interval="30m",
eager=True,
),
"groups": ["a", "a", "a", "b", "b", "a", "a"],
"values": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0],
}
)
print(df)
shape: (7, 3)
┌─────────────────────┬────────┬────────┐
│ time ┆ groups ┆ values │
│ --- ┆ --- ┆ --- │
│ datetime[μs] ┆ str ┆ f64 │
╞═════════════════════╪════════╪════════╡
│ 2021-12-16 00:00:00 ┆ a ┆ 1.0 │
│ 2021-12-16 00:30:00 ┆ a ┆ 2.0 │
│ 2021-12-16 01:00:00 ┆ a ┆ 3.0 │
│ 2021-12-16 01:30:00 ┆ b ┆ 4.0 │
│ 2021-12-16 02:00:00 ┆ b ┆ 5.0 │
│ 2021-12-16 02:30:00 ┆ a ┆ 6.0 │
│ 2021-12-16 03:00:00 ┆ a ┆ 7.0 │
└─────────────────────┴────────┴────────┘
업샘플링은 새 샘플링 간격을 정의하는 것으로 할 수 있어요. 업샘플링하면서 우리는 데이터가 없는 곳에 행을 추가하는 셈이라, 업샘플링만 하면 null이 있는 데이터프레임이 나옵니다. 이 null들은 채움 전략(fill strategy)이나 보간(interpolation)으로 채울 수 있어요.
업샘플링 전략 (Upsampling strategies)
이 예시에서는 원래 30분에서 15분으로 업샘플링한 다음, forward 전략으로 null을 이전의 non-null 값으로 대체합니다:
out1 = df.upsample(time_column="time", every="15m").fill_null(strategy="forward")
print(out1)
이번에는 null을 선형 보간(linear interpolation)으로 채우는 예시예요:
out2 = (
df.upsample(time_column="time", every="15m")
.interpolate()
.fill_null(strategy="forward")
)
print(out2)
더 알아보기 (Learn more)
- 다운샘플링의 핵심인 시간 기반 그룹핑은 그룹핑 (Grouping) 문서를 참고하세요.