Zero Labs
Industry News / AI

Time Series Analysis and Forecasting — Part 2: Data Preparation with Pandas

Source · Towards AI By Michalzarnecki

From the publisher’s feed, collected in the ZeroLabs newsroom.

Hi. Welcome to the second part of the time-series series. In Part 1 we covered the fundamentals — what a time series is, the three data layers (measurements, metadata, events), the three core characteristics (trend, seasonality, anomalies), and time windows — and walked through a complete Freezing-of-Gait classification pipeline on Parkinson’s sensor data.Now we shift from theory to the data preparation work that every real project starts with. This is the unglamorous part, but it’s where most of the quality of a forecast is actually won or lost. In this part I’ll walk you through:Pandas essentials for time series (with code)Date formats and time zones — why these trip people upDownsampling and upsampling (changing frequency)Filling missing values — forward, backward, rolling mean, interpolationSmoothingAutocorrelation and stationarityAll the code comes from a public notebook in the repository:Repository: https://github.com/mzarnecki/time-series-analysis Notebook for this part: time_series_analyze_with_pandas.ipynbLet’s start.Pandas for time series: the essentialsPandas is a Python library for data analysis and manipulation. It gives you two main structures — the two-dimensional DataFrame (a table) and the one-dimensional Series (a labelled vector) — and makes loading, filtering, aggregating, joining, and especially time-based operations straightforward.For time series, the workhorses are:datetime from the standard library — a representation of a date and timenumpy — the numerical backbone under Pandaspd.Series / pd.DataFrame with a DatetimeIndexWorking with datetimefrom datetime import datetimenow = datetime.now()now # datetime.datetime(2026, ...)now.year, now.month, now.day #(2026, 5, 9)A datetime has all the usual attributes — year, month, day, hour, minute. More importantly, you can subtract two datetimes and you get a timedelta:# period between two points in timedelta = datetime(2026, 1, 2) - datetime(2025, 7, 12, 8, 50)delta # datetime.timedelta(...)delta.days # number of whole daysdelta.seconds # remaining secondsThis is a small thing, but it’s the foundation of everything — windows, horizons, event durations all come down to arithmetic on dates.Formatting datesWhen you print a datetime, Python gives you a default ISO-like string. For custom formatting we use strftime with format codes:stamp = datetime(2026, 8, 3)str(stamp) # '2026-08-03 00:00:00'stamp.strftime("%Y-%m-%d") # '2026-08-03'stamp.strftime("%Y-%d-%m") # '2026-03-08' stamp.strftime("%Y-%d-%m %H:%M:%S")stamp.strftime("%A") # 'Monday'Notice %Y-%d-%m versus %Y-%m-%d. This swap is innocent-looking but catastrophic if you mix it up when parsing dates — more on this in a moment.Building a time series with PandasHere’s our first real time series: four dates, one random value per date.import pandas as pdimport numpy as npfrom datetime import datetimedates = [datetime(2026, 1, 2), datetime(2026, 1, 3), datetime(2026, 1, 4), datetime(2026, 1, 5)]ts = pd.Series(np.random.standard_normal(4), index=dates)tsThe ts object is a Series whose index is the sequence of dates. This is the key move: Pandas treats the index as the time axis, and every time-related method (resampling, rolling, shifting) operates along it.Statistics on a SeriesBecause we’re using a Pandas object, we immediately get a rich API. A common first step is describe:ts.describe()# count, mean, std, min, 25%, 50% (median), 75%, maxThat single call gives you the number of records, mean, standard deviation, min and max, the median, and the first and third quartiles — enough to get a feel for the series in one line.Arithmetic across aligned seriesWhen you add two series, Pandas aligns on the index — not on position. This is useful when you want to combine, say, two stores of the same chain or two sensors reporting the same quantity:ts + ts# values at matching dates are summedIf one series has an index value the other doesn’t, the result is NaN at that point. That's not a bug — it's saving you from silently adding things that don't belong together.Indexing and slicing by dateWith a DatetimeIndex you can select one value by its date or slice a range:ts['2026-01-04'] # value on that specific datets['2026-01-02':'2026-01-03'] # inclusive slicets['2026-01'] # whole month at onceNotice that partial strings work too — '2026-01' selects everything in January 2026. This is incredibly convenient for ad-hoc analysis.Aggregation over time: resample# average per year (toy example)ts.resample('YE').mean()resample is the time-aware cousin of groupby. 'YE' means "year-end" — you can also use 'D' (day), 'W' (week), 'ME' (month-end), 'H' (hour), '5min', and so on. We'll come back to this in the downsampling section.Shifting for lag featurests.shift(3) # each value moved 3 positions forward in timets.shift(-3) # and backwardThis is how you build lag features for ML models — “value from 3 days ago”, “value from 1 hour ago”.AutocorrelationFinally, autocorrelation — a measure of how strongly values of the series are related to their own past (at a given lag). High autocorrelation at a particular lag tells you that history carries real information about the future. Detection of cyclicity also shows up here: a strong spike at lag 7 on daily data strongly suggests a weekly pattern.We’ll return to this concept more formally in the autocorrelation section below.Date formats and time zones: why this is harder than it looksIn the notebook above you saw the same date written in several formats. In practice, parsing dates is a small industry of its own, and there are two main sources of pain.Problem 1: the many written forms of a dateThe same instant can be written as:2026-03-02 05:40:0002/03/2026 05:40Mar 2, 2026 05:40 AM2026-03-02T05:40:00Zor just 2026-03 (with a year+month only)Worse, the ordering itself is ambiguous. 03/04/2026 is March 4th in the US but April 3rd in most of Europe. If your script silently assumes one convention and the input uses the other, every date from the 13th of a month onward will throw an error — but dates below the 13th will parse silently as a different date than intended. This is a common and very annoying bug.Problem 2: time zonesThe timestamp 2026-03-02 05:40:00 on its own doesn't tell you which clock it was read from. It could be local time in Warsaw, New York, or Tokyo, or it could be UTC. On the other hand, 2026-03-02T05:40:00Z is unambiguous — the trailing Z ("Zulu time") means UTC+00:00, also called Coordinated Universal Time.When combining data from multiple sources, my rule of thumb is:Parse dates explicitly — don’t let Pandas guess the format, specify it.Convert everything to a single time zone (usually UTC) as soon as it hits the pipeline.Only at the presentation layer, convert to local time if needed.This sidesteps almost every class of bug related to daylight saving time, server time drifts, or records arriving from different continents.Time zones in Pandasimport pytztz = pytz.timezone("Europe/Warsaw")tz# generate a range during a DST transitionpd.date_range("2026-03-29 00:30", freq="H", periods=10, tz="Europe/Warsaw")Pandas will correctly handle the DST jump — you’ll see an hour disappear in the output. If you generate the same range in UTC and convert on display, nothing jumps, because UTC doesn’t do DST.Building date ranges# inclusive date range between two datesindex = pd.date_range("2027-04-01", "2027-06-01")# N periods starting from a datepd.date_range(start="2027-04-01", periods=20)# N periods ending at a datepd.date_range(end="2027-06-01", periods=20)# business month ends between two datespd.date_range("2027-01-01", "2028-12-01", freq="BME")Date arithmetic with offsetsfrom pandas.tseries.offsets import Day, MonthEndnow = datetime(2026, 6, 22)now - 10 * Day() # ten days earliernow + MonthEnd(2) # end of the month, two months aheadOffsets are nicer than raw timedelta because they understand things like "month end" or "business day", which naive day-counting can't express.Changing frequency: downsampling and upsamplingOnce dates and time zones are under control, a very common next step is to align the frequency of the series. Real data is rarely already on the grid you want.There are two basic operations: going from denser to sparser data (downsampling), and from sparser to denser data (upsampling).DownsamplingDownsampling means going from higher-resolution data (e.g., multiple entries per day) to a coarser time grid (e.g., daily values). The usual mechanism is aggregation — typically sum or mean, depending on the semantics of the variable:For sales or event counts, a sum over the window is natural (total for the day).For temperature or environmental readings, mean / min / max tends to be more useful.Downsampling reduces the number of records, simplifies downstream processing, and often clarifies trend and seasonality. The aggregates can also become features in their own right — daily sum, weekly mean, daily max, variance in a window.Let’s build a small example. First a 5-day series with random values:import pandas as pdimport numpy as npdates = pd.date_range("2026-01-01", periods=5, freq="D")ts = pd.Series(np.random.standard_normal(5), index=dates)tsThen downsample to 5-day aggregates by sum:ts.resample("5D").sum()The full series collapses into a single 5-day sum. The resample call defines the bucket, the aggregation call (sum, mean, max, count, ...) defines how to reduce the bucket.The closed parameterts.resample("5D", closed="right").sum()closed="right" tells Pandas which end of the bucket interval is closed (included). By default left is closed and right is open — [start, end). With closed="right", a point sitting exactly on the bucket boundary belongs to the previous bucket. This matters when observations fall exactly on boundaries (e.g., at midnight).UpsamplingUpsampling is the opposite: going from sparser to denser data. For example, from daily values to hourly values. This creates new time points with no measurement — you have to decide how to fill them.Common reasons to upsample:Aligning several series with different native frequencies onto a common gridForcing an irregular series into a regular grid required by a modelImportant caveat: upsampling does not add information. It only creates new timestamps that you then have to fill with some rule. Always keep track of which values were measured and which were imputed.A minimal upsampling example with forward fill:dates = pd.date_range("2026-01-01", periods=5, freq="D")ts = pd.Series(np.random.standard_normal(5), index=dates)# upsample to 12h resolution, forward-fill the gapsts.resample("12H").ffill()We just doubled the number of timestamps. Every second value is a copy of the previous measured one.Limiting how far forward-fill can reachSometimes we want “last known value” to only be valid for a short while. If the sensor hasn’t reported in 3 hours, the last reading probably shouldn’t be used for the next 48 hours. Pandas supports a limit parameter for that:ts.resample("12H").ffill(limit=2)Now forward fill will only propagate the last known value for two new points; beyond that, the series contains NaN and you're forced to handle it explicitly.Resample on DataFrame with a chosen time columnIf your time information isn’t in the index, set it before resampling:N = 15times = pd.date_range("2027-10-24 00:00:00", freq="1min", periods=N)df = pd.DataFrame({"czas": times, "value_1": np.arange(N), "value_2": np.arange(N)})df.set_index("czas").resample("5min").count()OHLC: a neat resample trick for financeFor financial data you sometimes want the Open, High, Low, Close of each bucket. Pandas has this built in:ts = pd.Series(np.random.permutation(np.arange(len(dates))), index=dates)ts.resample("5min").ohlc().ffill()One call and you get four columns — open (first value of the bucket), high (max), low (min), close (last).Missing values: four common strategiesIn real time series, missing values are almost inevitable. Sensor failure, system outage, network hiccup, or simply no data collected in that interval. Before we can model, we have to decide how to treat these gaps.There are four popular strategies.1. Forward fillA missing point takes the last known value from the past. On a plot this looks like a flat line holding the previous level until a new observation arrives. Simple and widely used in financial or system data where values tend to change slowly and a missing tick doesn’t imply a real change.ts.ffill()2. Backward fillA missing point takes the next known value from the future. Useful for historical analyses, but dangerous in predictive modelling because it introduces look-ahead bias — you’re letting the model “see” information that wouldn’t be available at prediction time.ts.bfill()3. Rolling meanA missing value is replaced with the average of its neighbours. This avoids the blocky look of forward-fill and keeps the series smooth. Good when single points are missing and you don’t want them to visibly distort the trend.ts.fillna(ts.rolling(window=5, min_periods=1, center=True).mean())4. InterpolationInterpolation reconstructs the missing value assuming some relation between the neighbours. The simplest is linear interpolation — the missing point lies exactly on the line between its neighbours. More sophisticated variants exist (polynomial, spline).ts.interpolate(method="linear")Interpolation is particularly popular in measurement data — meteorology, IoT sensors, continuous physical signals.How to chooseThere’s no universal answer. For slow-changing financial ticks, forward fill is usually fine. For physical measurements with a clear continuous behavior, interpolation is often better. For data that naturally has a “zero” state when nothing is happening (e.g., order count in a minute), filling missing values with zero might be correct.The key point: always understand what your missing-value strategy assumes. The method you pick influences the downstream model, and it’s easy to hide real data-quality issues under a convenient fill.SmoothingOnce data is aligned in time and frequency, and gaps are filled, a common next step is smoothing — reducing the effect of noise, single spikes, and outliers.The idea is simple: replace each value with some weighted combination of its neighbours. The result looks calmer and the trend is easier to see.A classic example is the rolling mean:close_px_all = pd.read_csv("../data/stock.csv", parse_dates=True, index_col=0)close_px = close_px_all["MSFT"]# raw priceclose_px.plot()# 250-day rolling meanclose_px.rolling(250).mean().plot()That produces two curves — the raw price and its 250-day smoothed version. You lose local detail but gain a much cleaner view of the long-term trend.Smoothing is used for two purposes: preparing data for a model (to reduce variance in features) and producing readable plots. A third, related use: computing a rolling volatility:std250 = close_px.pct_change().rolling(250, min_periods=10).std()# "250-day rolling standard deviation of daily returns"std250.plot()A warningSmoothing has to be applied with care. If you smooth too aggressively you can erase short but important events — spikes, brief anomalies, the very patterns you may be trying to detect. As with every other preprocessing step, the right amount depends on what you’re trying to achieve, so pick the method and parameters with the downstream task in mind.Autocorrelation and stationarityWith data prepared and optionally smoothed, the next step is to check how the series depends on its own history and whether its behaviour is stable over time. These are two related concepts: autocorrelation and stationarity.AutocorrelationAutocorrelation measures how strongly the current value of the series is related to its own past values — the same signal shifted by some lag. High autocorrelation at specific lags means history contains useful information about the future, and it’s worth considering features like “value one day ago, value seven days ago”, or models that explicitly use lagged values (like ARIMA).In Pandas, a quick way to get a feel for autocorrelation at a given lag:ts.autocorr(lag=1)ts.autocorr(lag=7)For a proper visual assessment, the standard tool is the autocorrelation function (ACF) plot from statsmodels:from statsmodels.graphics.tsaplots import plot_acfplot_acf(close_px.dropna(), lags=40)A clear spike at lag 7 on daily data strongly suggests weekly seasonality. Gradually decaying spikes from lag 1 onwards suggest that each value is close to the previous one — typical of trending data.StationarityA series is stationary when its statistical properties — mean, variance, autocorrelation — don’t change in time. Stationarity is required (or at least heavily preferred) by many classical forecasting models.When you have a strong trend, or variance that grows over time, the series is clearly not stationary. The common remedy is to transform the series — for example by taking first differences:# first differences remove a linear trendts_diff = ts.diff().dropna()Or taking the percent change:returns = ts.pct_change().dropna()For stock prices this is particularly natural — raw prices are extremely non-stationary, but daily returns are much closer to stationary.If you want a formal statistical test for stationarity, the Augmented Dickey-Fuller (ADF) test is a standard tool:from statsmodels.tsa.stattools import adfullerresult = adfuller(ts.dropna())print(f"ADF statistic: {result[0]:.4f}")print(f"p-value: {result[1]:.4f}")A low p-value (below 0.05) is evidence that the series is stationary. A high p-value suggests you probably need to difference or transform before modelling.Putting it all togetherThe preprocessing steps above — parsing dates, resampling to a consistent frequency, filling missing values, smoothing, and checking autocorrelation and stationarity — form a standard front-end to nearly every time-series project. I’d estimate at least half the work in a real project lives in these steps.The thing that’s easy to forget when you’re deep in feature engineering: every choice here is a modeling choice. “We forward-fill the daily gaps” is a statement about the world (i.e., the value doesn’t change when we’re not looking). “We smooth with a 250-day rolling mean” removes some of the signal along with the noise. If the choice is wrong for your problem, no fancy downstream model will save you.A workflow I find reliable:Load, parse dates explicitly, convert to a single time zone.Inspect — plot a few sessions, check metadata distributions, look for obvious trouble (start-of-session noise, long gaps, suspicious duplicates).Resample to a consistent frequency. Choose aggregation that fits the variable semantics (sum vs. mean).Fill missing values deliberately, and keep a marker column for which values were imputed.Smooth only when it clearly helps the downstream task, and only as much as needed.Check autocorrelation and stationarity — these tell you what kind of model makes sense.Only once you’ve been through those steps does it make sense to start fitting models. Which is exactly where we’ll go in Part 3.What’s nextIn Part 3 of the series we’ll cover the actual forecasting models:Classical statistical models — ARIMA, SARIMA, ETSProphet for business forecastingTime Series Transformer — the modern neural-network approachHow to evaluate forecasts — MAE, RMSE, MAPE, WAPE, MASE, Column ImpactProbabilistic forecasting with quantile lossA walkthrough of an LSTM-based stock-price forecasterA walkthrough of a siren classification pipeline using FFT featuresAll the code examples live in the repository:https://github.com/mzarnecki/time-series-analysisSee you in Part 3.See also Part 1 if you started from this chapter.Time Series Analysis and Forecasting — Part 2: Data Preparation with Pandas was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.