時系列分析に役立つPythonスクリプト5選
KDnuggets は、不規則な間隔のデータ処理や異常検知など時系列分析の主要課題を解決する Python スクリプト 5 つを紹介し、実務での即座な適用を可能にするツールキットを提供した。
キーポイント
不規則な時間間隔データの正規化と集約
センサーデータやトランザクションログなど、一貫性のないタイムスタンプを持つデータを指定周波数にリサンプリングし、欠損値の処理や集計関数の適用を自動化するスクリプト。
時系列データの異常検知機能
データ内の突発的なスパイクやノイズを特定し、下流分析への悪影響を防止するための異常検出アルゴリズムを実装したツール。
トレンドと季節性の分離
複雑な時系列データからノイズを取り除き、明確なトレンドや季節パターンを抽出して可視化・分析しやすくする処理を提供する。
複数シリーズ間の相関関係の解析
単なる視覚的なスキャンでは不十分な、複数の時系列データ間の相互関係を定量的に理解するための分析手法を含む。
時系列の構成要素を分離
長期トレンド、季節性パターン、不規則なノイズという3つの成分に分解し、各要素を個別に分析可能にする。
加法・乗法モデルのサポート
データの特性に応じて選択可能な、加法(additive)および乗法(multiplicative)の両方の分解モデルに対応している。
SARIMA モデルの自動化と評価
このスクリプトは時系列データに SARIMA モデルを適用し、予測値、信頼区間、検証期間における精度指標を含む結果ファイルを出力します。
重要な引用
Working with time series data involves a consistent set of tasks.
Real-world time series data rarely arrives at uniform intervals.
These five Python scripts handle these common time series tasks.
A time series is usually a combination of several components: a long-term trend, a repeating seasonal pattern, and irregular residual noise.
Analyzing the series as a whole makes it hard to understand any one component clearly.
Producing a forecast from a time series typically involves model selection, parameter tuning, and validation steps that require statistical knowledge to get right.
影響分析・編集コメントを表示
影響分析
この記事は、データサイエンティストやエンジニアが時系列分析の基礎的な前処理タスクに費やす時間を大幅に削減する実用的なリソースを提供しています。特に、不規則な間隔のデータを扱う現場での即座の適用が可能であり、分析の信頼性を高めるための標準化されたアプローチを促進します。
編集コメント
特定の AI モデルの最新動向ではありませんが、データ分析基盤を強化するための実用的なコードスニペットとして非常に価値が高い記事です。
image**
# イントロダクション
時系列データを扱うには、一貫したタスクセットが必要です。生データは不規則な間隔で到着し、リサンプリングが必要となります。分析結果を歪める前に異常なスパイクを特定する必要があります。トレンドや季節パターンをノイズから分離することも求められます。また、複数の時系列がある場合、それらが互いにどのように関連しているかを理解するには、単なる視覚的なスキャンだけでは不十分です。
これら 5 つの Python スクリプトは、これらの一般的な時系列タスクを処理するために設計されています。標準的な CSV または Excel 入力と連携し、クリーンな出力を生成し、異なるデータセットに対して設定が容易になるように作られています。
# 1. 不規則な時系列のリサンプリングと集約
// 課題点
現実世界の時系列データが均一な間隔で到着することはめったにありません。センサーの読み取り値、トランザクションログ、イベントストリームには欠落、重複、不整合なタイムスタンプが存在します。意味のある分析を行う前に、データを一定の頻度に合わせる必要があります。
// スクリプトの機能
日付時刻列と 1 つ以上の数値列を含む CSV または Excel ファイルを受け取り、指定した頻度でリサンプリングし、各カラムに対して集約関数を適用します。欠落部分を埋めたりフラグを立てたりし、変更内容のサマリー付きでクリーンな出力ファイルを生成します。
// 動作原理
このスクリプトは、pandas を用いて日付時刻列を解析し、それをインデックスとして設定します。また、設定可能な頻度文字列を用いて resample() 関数を利用します。各列ごとの集計メソッドは設定ファイルで定義されるため、温度データのカラムでは平均値(mean)を、売上データのカラムでは合計値(sum)を使用することが可能です。リサンプリング後に生じる欠損区間は、設定に応じて前方補完(forward-fill)、補間(interpolation)、または明示的な NaN フラグ付けのいずれかで処理されます。ギャップレポートには、元のデータに欠落していたすべての区間がリストアップされます。
# 2. 時系列データにおける異常検出
// 課題点
時系列データにおける単一の異常なスパイクや急落は、平均値を歪め、下流のモデルを破綻させ、真のトレンドを隠してしまう可能性があります。これらのポイントを、プロットや生データをスキャンして手動で特定することは、実用的な規模のデータ量においては非現実的です。
// スクリプトの機能
時系列ファイル内の 1 つ以上の数値カラムを走査し、選択した 3 つの検出手法(z スコア、四分位範囲(IQR)、ローリング統計)を用いて、期待される範囲外にあるデータポイントをフラグ付けします。異常フラグ付きのアノテーション済みファイルと、別個のサマリーレポートを出力します。
// 動作原理
z スコア法は、標準化された値が設定可能な閾値(デフォルト±3)を超えた点を検出します。四分位範囲(IQR)法は、1.5 倍の四分位範囲の外側にある点を検出します。ローリング法は、設定可能なウィンドウ内で移動平均と標準偏差を計算し、局所的な文脈から大きく逸脱する点を検出します。これは、強いトレンドや季節性を有する時系列データに有用です。これら 3 つの手法は同時に実行可能で、出力列には各点がどの手法によって検出されたかを記録します。オプションの --plot フラグを使用すると、異常値が強調表示されたチャートが各列ごとに保存されます。
# 3. シリーズのトレンド、季節性、および残差への分解
// 課題点
時系列データは通常、長期的なトレンド、繰り返される季節パターン、不規則な残差ノイズという複数の構成要素の組み合わせです。シリーズ全体を分析すると、各構成要素を明確に理解することが困難になります。
// スクリプトの機能
数値列に対して古典的な時系列分解を適用し、観測されたシリーズをトレンド、季節性、および残差成分に分離します。加法モデルと乗法モデルの両方をサポートします。各成分は出力ファイル内の別々の列としてエクスポートされ、マルチパネルチャートも保存されます。
// 動作原理
このスクリプトは、必要に応じて対象列を一定の頻度でリサンプリングした後に statsmodels.tsa.seasonal.seasonal_decompose() を使用します。分解周期は設定可能です。季節変動の大きさがほぼ一定である系列には加法分解が、トレンドレベルに応じて変動がスケールする系列には乗法分解が適しています。出力される Excel ファイルには、元の時系列データと抽出された 3 つの成分が併記されます。保存されたチャートでは、4 つのパネルが縦に積み重ねて表示されます。
# 4. 季節性自己回帰和分移動平均による予測
// 課題
時系列から予測値を作成するには、通常、統計的知識を要するモデル選択、パラメータ調整、検証のステップが含まれます。毎回ゼロからこれを設定するのは時間がかかり、非公式に行うと信頼性或いは再現性が低い予測結果となりがちです。
// スクリプトの機能
時系列列に対して季節性自己回帰統合移動平均 (SARIMA) モデルを適合させ、設定可能な期間数分の予測を生成し、予測値、信頼区間、および保留された検証期間における基本的な精度指標を含む結果を出力ファイルに書き出します。オプションで Akaike 情報量基準 (AIC) の最小化を用いてモデルパラメータを自動選択することも可能です。
// 仕組みについて
このスクリプトは、モデル適合に statsmodels.tsa.statespace.sarimax.SARIMAX を使用します。--auto-order が設定されている場合、設定可能な範囲の ARIMA および季節パラメータに対して軽量なグリッドサーチを実行し、AIC が最小となる組み合わせを選択します。時系列データは、期間数として設定可能なトレーニングセットと保留されたテストセットに分割されます。最終モデルが全系列で再適合される前に、テストセット上で平均絶対誤差 (MAE) と二乗平均平方根誤差 (RMSE) を用いて精度が報告されます。結果には点予測値と 95% 信頼区間が含まれます。保存される予測チャートには、歴史的時系列、テスト期間の実績値対予測値、および信頼帯付きの将来予測が表示されます。
# 5. 複数の時系列データの比較
// 課題点
関連する複数の時系列データ(異なる製品、地域、センサー、または指標)を扱う際、それらがどのように連動して動くかを理解するには、単に同じチャート上に描画するだけでは不十分です。相関分析、ラグ関係、および整合性の取れた要約統計量の計算が必要となりますが、多数のデータペアに対してこれらを逐一実行しようとすると、作業が非常に煩雑になりがちです。
// スクリプトの機能
複数の時系列データを格納したファイルを読み込み、共通の周波数に整列させた上で、ペアごとの相関分析、ラグ分析(クロス相関を構成可能なラグ範囲まで計算)、および並列表示された要約統計量テーブルを含む多タブ形式の比較レポートを生成します。また、最も高い相関を示すペアについてはチャートも自動生成されます。
// 動作原理
このスクリプトは、リサンプリング後に pandas を使用してすべての列を共有の日時インデックスに整列させます。ペアごとのピアソン相関とスピアマン相関が計算され、相行列表に書き込まれます。クロス相関は各ペアに対して設定可能な最大ラグまで計算され、各ペアのピークが生じるラグが特定されます。これは先行・後行関係を見つけるのに役立ちます。サマリータブには、各時系列の平均、標準偏差、最小値、最大値、およびトレンド方向(線形フィットからの正/負の傾き)が含まれています。最も相関の高い上位 5 つのペアそれぞれが、専用のチャートタブにデュアル軸ラインチャートとして表示されます。
まとめ
**
これら 5 つのスクリプトは、時系列データを取り扱う際に必要な中核的なタスクを網羅しています。これらは独立して使用することも、順次(リサンプリング→異常検出→分解→予測→シリーズ間比較)に使用することを想定して設計されています。
使い始めるには、まず使用するスクリプトをダウンロードし、その README ファイルに記載されたすべての依存関係をインストールしてください。次に、スクリプトの上部にある設定セクションを更新して、特定のデータや列名に合わせて調整します。完全なデータセットで実行する前に、小さなサンプルでスクリプトをテストし、出力が正しいことを確認してください。結果に満足したら、スケジュールを設定したり、既存のデータパイプラインに統合したりできます。
分析を楽しんでください!
Bala Priya C はインド出身の開発者かつ技術ライターです。数学、プログラミング、データサイエンス、コンテンツ制作が交差する領域での作業を好んでいます。彼女の関心分野および専門知識には、DevOps、データサイエンス、自然言語処理(NLP)が含まれます。読書、執筆、コーディング、そしてコーヒーを楽しむのが好きです。現在、チュートリアル、ハウツーガイド、意見記事などを執筆することで、開発者コミュニティに知識を共有し、自らも学び続ける活動を行っています。また、魅力的なリソースの概要やコーディングチュートリアルも作成しています。
原文を表示

**
# Introduction
Working with time series data involves a consistent set of tasks. Raw data arrives at irregular intervals and needs resampling. Anomalous spikes need to be identified before they distort any downstream analysis. Trends and seasonal patterns need separating from noise. And when you have multiple series, understanding how they relate to each other takes more than a quick visual scan.
These five Python scripts handle these common time series tasks. They are designed to work with standard CSV or Excel inputs, produce clean outputs, and be straightforward to configure for different datasets.
You can get all the scripts on GitHub.
# 1. Resampling and Aggregating Irregular Time Series
// The Pain Point
Real-world time series data rarely arrives at uniform intervals. Sensor readings, transaction logs, and event streams have gaps, duplicates, and inconsistent timestamps. Before any meaningful analysis, the data needs to be aligned to a consistent frequency.
// What the Script Does
Takes a CSV or Excel file with a datetime column and one or more value columns, resamples to a frequency you specify, and applies aggregation functions per column. Fills or flags gaps and writes a clean output file with a summary of what was changed.
// How It Works
The script parses the datetime column with pandas**, sets it as the index, and uses resample() with configurable frequency strings. Per-column aggregation methods are defined in a config, so a temperature column can use mean while a sales column uses sum. Missing intervals after resampling are handled with forward-fill, interpolation, or explicit NaN flagging depending on your setting. A gap report lists every interval where data was absent in the original.
⏩ Get the time series resampler script
# 2. Detecting Anomalies in Time Series Data
// The Pain Point
A single anomalous spike or drop in a time series can skew averages, break downstream models, and mask real trends. Identifying these points manually by scanning plots or raw values is impractical at any meaningful data volume.
// What the Script Does
Scans one or more numeric columns in a time series file and flags data points that fall outside expected bounds using a choice of three detection methods: z-score, interquartile range (IQR), or rolling statistics. Outputs an annotated file with anomaly flags and a separate summary report.
// How It Works
The z-score method flags points where the standardized value exceeds a configurable threshold (default ±3). The interquartile range (IQR) method flags points outside 1.5× the interquartile range. The rolling method computes a moving mean and standard deviation over a configurable window and flags points that deviate significantly from the local context. This is useful for series with strong trends or seasonality. All three can be run together; the output column records which method flagged each point. An optional --plot flag saves a chart for each column with anomalies highlighted.
⏩ Get the anomaly detector script
# 3. Decomposing a Series into Trend, Seasonality, and Residuals
// The Pain Point
A time series is usually a combination of several components: a long-term trend, a repeating seasonal pattern, and irregular residual noise. Analyzing the series as a whole makes it hard to understand any one component clearly.
// What the Script Does
Applies classical time series decomposition to a numeric column, separating the observed series into trend, seasonal, and residual components. Supports both additive and multiplicative decomposition models. Exports each component as a column in the output file and saves a multi-panel chart.
// How It Works
The script uses statsmodels.tsa.seasonal.seasonal_decompose() on the target column after resampling to a consistent frequency if needed. The decomposition period is configurable. Additive decomposition suits series where seasonal variation is roughly constant in magnitude; multiplicative suits series where it scales with the trend level. The output Excel file contains the original series alongside the three extracted components. The saved chart shows all four panels stacked.
⏩ Get the time series decomposition script
# 4. Forecasting with Seasonal AutoRegressive Integrated Moving Average
// The Pain Point
Producing a forecast from a time series typically involves model selection, parameter tuning, and validation steps that require statistical knowledge to get right. Setting this up from scratch each time is time-consuming, and doing it informally produces forecasts that are hard to trust or reproduce.
// What the Script Does
Fits a seasonal autoregressive integrated moving average (SARIMA) model to a time series column, generates a forecast for a configurable number of periods, and writes results to an output file including the forecast values, confidence intervals, and basic accuracy metrics on a held-out validation period. Optionally auto-selects model parameters using Akaike information criterion (AIC) minimization.
// How It Works
The script uses statsmodels.tsa.statespace.sarimax.SARIMAX for model fitting. When --auto-order is set, it performs a lightweight grid search over a configurable range of ARIMA and seasonal parameters, selecting the combination with the lowest AIC. The series is split into a training set and a held-out test set configurable as a number of periods. Accuracy is reported on the test set using mean absolute error (MAE) and root mean squared error (RMSE) before the final model is re-fit on the full series to produce the forward forecast. Results include the point forecast and 95% confidence intervals. A forecast chart is saved showing the historical series, the test period actuals vs. predictions, and the forward forecast with confidence bands.
⏩ Get the SARIMA forecasting script
# 5. Comparing Multiple Time Series
// The Pain Point
When working with several related time series — different products, regions, sensors, or metrics — understanding how they move together requires more than viewing them on the same chart. Correlation analysis, lag relationships, and aligned summary statistics all need computing, and doing this across many pairs of series quickly becomes unwieldy.
// What the Script Does
Takes a file with multiple time series columns, aligns them to a common frequency, and produces a multi-tab comparison report covering pairwise correlations, lag analysis (cross-correlation up to a configurable lag), and a side-by-side summary statistics table. Charts are generated for the top correlated pairs.
// How It Works
The script uses pandas to align all columns to a shared datetime index after resampling. Pairwise Pearson and Spearman correlations are computed and written to a correlation matrix tab. Cross-correlation is computed for each pair up to a configurable maximum lag, identifying the lag at which each pair peaks, which is useful for finding leading/lagging relationships. A summary tab includes mean, standard deviation, min, max, and trend direction (positive/negative slope from a linear fit) for each series. The top five most correlated pairs each get a dual-axis line chart in a dedicated charts tab.
⏩ Get the multi-series comparison script
# Wrapping Up
**
These five scripts cover the core tasks involved in working with time series data. They are designed to be used independently or sequentially: resample first, detect anomalies, decompose, forecast, then compare across series.
To get started, first download the script you plan to use and install all the dependencies listed in its README file. Next, update the configuration section at the top of the script so it aligns with your specific data and column names. Before running it on your full dataset, test the script on a small sample to confirm the output is correct. Once you're satisfied with the results, you can schedule it or integrate it into your existing data pipeline.
Happy analyzing!
Bala Priya C** is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she's working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource overviews and coding tutorials.
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み