Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To analyze time series data in Python, first put observations on a correctly parsed, chronologically sorted date index and establish what each row represents. Then inspect trend and seasonality, check whether the series is stationary, and—if forecasting—evaluate predictions on later observations that were kept out of model fitting. These five adaptable scripts cover those steps with pandas, statsmodels, scikit-learn, and Prophet. They are examples, not tested or production-ready software; confirm current package APIs and adapt them to your data.

1. Parse timestamps, sort observations, and resample

Before modeling, make the date column usable as a time index and check the observation cadence. Resampling can group observations into a regular interval, but it cannot determine what missing periods mean in your data. The right aggregation depends on the measurement: summing transactions by day differs from averaging a sensor reading.

import pandas as pd

# Example input columns: timestamp, value
df = pd.read_csv("observations.csv")
df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce")
df["value"] = pd.to_numeric(df["value"], errors="coerce")
df = df.dropna(subset=["timestamp", "value"])
df = df.sort_values("timestamp").set_index("timestamp")

# Example only: aggregate a numeric measure to daily sums.
daily = df["value"].resample("D").sum()
print(daily.index.freq)
print(daily.isna().sum())

Change "D" and sum() to match the source cadence and meaning of the data; for example, an average may be more appropriate for repeated measurements. Resampling bins observations and applies an aggregation rule. It does not automatically establish whether an empty bin means zero activity, an unrecorded value, or a missing data collection period. Decide how to handle those cases before filling gaps or interpreting later results. See the pandas time-series guide for date and frequency functionality.

2. Decompose the series into trend, seasonality, and residuals

Decomposition helps answer whether a series appears to combine a longer-term movement with a recurring pattern. The residual is what remains after the chosen trend and seasonal components are accounted for; it is not automatically noise or proof that the model is adequate. Statsmodels documents decomposition methods and examples, including multi-seasonal approaches.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
from statsmodels.tsa.seasonal import seasonal_decompose

# Use a regular series and set period to the number of observations
# in one expected seasonal cycle.
result = seasonal_decompose(daily, model="additive", period=7)
result.plot()

This illustrative weekly period assumes daily observations with a weekly cycle; it is not a universal default. Choose a period that matches the cadence and a plausible seasonal cycle, and ensure the history covers enough cycles to make the pattern interpretable. An additive decomposition is suited to a pattern whose seasonal swings are roughly constant in size; multiplicative decomposition represents seasonal variation that changes in proportion to the series level and requires suitable positive values. If seasonality is not stable or there are several seasonal cycles, consider an approach appropriate to that structure rather than forcing a single-period decomposition. Statsmodels’ examples cover decomposition alongside other time-series methods.

3. Check stationarity and consider detrending

Stationarity diagnostics help assess whether a series’ statistical behavior changes over time, a consideration for some time-series models. The Augmented Dickey–Fuller (ADF) and KPSS tests use different null hypotheses, so their results should be interpreted together with a plot, domain context, and the intended model—not as a universal pass/fail certification.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
from statsmodels.tsa.stattools import adfuller, kpss

series = daily.dropna()
adf_stat, adf_p, *_ = adfuller(series)
kpss_stat, kpss_p, *_ = kpss(series, regression="c", nlags="auto")

print("ADF statistic and p-value:", adf_stat, adf_p)
print("KPSS statistic and p-value:", kpss_stat, kpss_p)

In broad terms, ADF tests a unit-root null, while KPSS tests a stationarity null under the specified regression form. A small p-value therefore points in different directions for the two tests. Trends, structural changes, seasonal effects, missing observations, and the chosen test settings can all affect interpretation. If the series is nonstationary for a model that expects stationarity, investigate transformations or detrending and reassess; do not assume a test result alone identifies the right remedy. Statsmodels lists stationarity and detrending examples in its examples and exposes time-series tools in its API reference.

4. Turn past observations into lagged forecasting features

A feature-based forecast treats time-series prediction as supervised learning: past values become input columns, and a later value is the target. The split must preserve chronology. Randomly shuffling observations can let information from the future influence training or validation, producing an evaluation that does not represent forecasting into the future.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error

# daily is a regular, ordered pandas Series.
data = pd.DataFrame({"y": daily})
data["lag_1"] = data["y"].shift(1)
data["lag_7"] = data["y"].shift(7)
data["day_of_week"] = data.index.dayofweek
supervised = data.dropna()

# Hold the latest observations out; do not shuffle.
split = int(len(supervised) * 0.8)
train, test = supervised.iloc[:split], supervised.iloc[split:]
features = ["lag_1", "lag_7", "day_of_week"]
model = HistGradientBoostingRegressor()
model.fit(train[features], train["y"])
prediction = model.predict(test[features])
print("MAE:", mean_absolute_error(test["y"], prediction))

The example predicts each held-out row using lag values already observed in the series. For a multi-step forecast made all at once, future lag values are not yet known: decide whether to predict recursively, use a direct multi-horizon setup, or otherwise construct features using only information available at each forecast origin. Calendar features also need to be available for the forecast dates. Compare against a simple baseline and use a time-aware evaluation design suited to the deployment horizon; a single chronological holdout is only one evaluation choice. Scikit-learn’s examples include lagged-feature forecasting and time-related feature engineering.

5. Fit and inspect a Prophet forecast

Prophet provides a forecasting workflow based on a dataframe with a datestamp column named ds and a numeric target named y. Its additive model can represent nonlinear trend, yearly, weekly, and daily seasonality, as well as holiday effects. The project says it works best when seasonal effects are strong and several seasons of historical data are available; suitability depends on the actual series and forecast task.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
import pandas as pd
from prophet import Prophet

# source contains timestamp and value columns.
prophet_data = source.rename(
    columns={"timestamp": "ds", "value": "y"}
)[["ds", "y"]].copy()
prophet_data["ds"] = pd.to_datetime(prophet_data["ds"])
prophet_data["y"] = pd.to_numeric(prophet_data["y"], errors="coerce")
prophet_data = prophet_data.dropna().sort_values("ds")

model = Prophet()
model.fit(prophet_data)
future = model.make_future_dataframe(periods=30, freq="D")
forecast = model.predict(future)
model.plot(forecast)
model.plot_components(forecast)

Here, periods=30 requests 30 future dates and freq="D" sets a daily cadence; change both to fit the data and the forecast horizon. The plotted forecast and component plots help inspect the fitted trend and seasonal contributions, but visual fit on historical observations is not a substitute for evaluation on dates excluded from fitting. For a forecast assessment, reserve later observations before fitting and compare predictions with their actual values. Follow the Prophet Quick Start for the documented input and workflow, and consult the Prophet project README for project guidance.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How to choose a time-series workflow

These scripts answer different questions and are not interchangeable model contests. Statsmodels documents classical approaches such as ARIMA, exponential smoothing, decomposition, and stationarity checks; scikit-learn supports forecasts built from engineered features; Prophet offers a seasonal additive forecasting workflow. Select based on the structure and purpose of the data, then judge forecasts using a time-ordered evaluation rather than assuming any method is more accurate by default.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
  • Cadence and history: Identify whether observations are hourly, daily, monthly, or irregular, and how many complete seasonal cycles are present. A period or frequency must correspond to the observations actually available.
  • Recurring patterns: If a repeating cycle is evident, decomposition can help expose it, while a forecast method must be configured or engineered to represent it.
  • Feature design: Lagged-feature models require deliberate decisions about which historical values and calendar attributes are known at prediction time.
  • Interpretability: Decomposition provides explicit trend, seasonal, and residual views; a predictive model’s accuracy alone may not explain the series’ structure.
  • Evaluation: Keep future observations out of training, use a horizon that matches the real forecast need, and compare methods only under a common time-aware validation setup.

For broader method details, consult the statsmodels examples, statsmodels API reference, and the statsmodels time-series documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.