Zeitreihen neu abtasten
Aggregieren Sie Tagesdaten mit resample('ME').sum() auf Monatsebene und tasten Sie Zeitreihen mit Vorwärtsauffüllen hoch, um fehlende Intervalle zu ergänzen.
Zeitreihen neu abtasten ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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 rowsDownsampling: 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 31OHLC 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.
Häufig gestellte Fragen
Ist die Lektion „Zeitreihen neu abtasten“ kostenlos?
Ja — der vollständige Text von „Zeitreihen neu abtasten“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Zeitreihen neu abtasten“?
Aggregieren Sie Tagesdaten mit resample('ME').sum() auf Monatsebene und tasten Sie Zeitreihen mit Vorwärtsauffüllen hoch, um fehlende Intervalle zu ergänzen. Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?
Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „Zeitreihen neu abtasten“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?
Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- DatetimeIndex und Periodenbereiche
- Zeitreihen neu abtasten
- Verschiebungen und Lag-Features
- Zeitmerkmale extrahieren