Bird
Raised Fist0
ML Pythonml~5 mins

Stationarity and differencing in ML Python

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

Stationarity means a data pattern that does not change over time. Differencing helps make data stationary by removing trends or seasonality.

When you want to predict future sales based on past sales data that changes over time.
When analyzing temperature data that shows seasonal patterns.
When working with stock prices that have trends and fluctuations.
When preparing time series data for models that require stable patterns.
When you want to compare data points fairly over time without trend effects.
Syntax
ML Python
differenced_data = original_data.diff(periods=1)

diff() subtracts the previous value from the current value to remove trends.

The periods parameter controls how many steps back to subtract.

Examples
Subtracts the previous value from each value (lag 1) to remove simple trends.
ML Python
data.diff()
Subtracts the value two steps before to remove longer-term trends.
ML Python
data.diff(periods=2)
Removes the first missing value created by differencing to keep clean data.
ML Python
data.diff().dropna()
Sample Model

This code creates a time series with a trend, tests if it is stationary, then applies differencing to remove the trend and tests stationarity again. The p-value shows if the data is stationary (lower than 0.05 means stationary).

ML Python
import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller

# Create a simple time series with a trend
np.random.seed(0)
time = pd.Series(np.arange(10))
data = time * 2 + np.random.normal(size=10)

# Check if data is stationary using Augmented Dickey-Fuller test
result_before = adfuller(data)

# Apply differencing to remove trend
diff_data = data.diff().dropna()

# Check stationarity again
result_after = adfuller(diff_data)

print(f"ADF Statistic before differencing: {result_before[0]:.4f}")
print(f"p-value before differencing: {result_before[1]:.4f}")
print(f"ADF Statistic after differencing: {result_after[0]:.4f}")
print(f"p-value after differencing: {result_after[1]:.4f}")
OutputSuccess
Important Notes

Differencing can create missing values at the start; always handle them (e.g., drop or fill).

Stationarity is important because many time series models assume stable data patterns.

Sometimes multiple differencing steps are needed to achieve stationarity.

Summary

Stationarity means data patterns stay consistent over time.

Differencing removes trends or seasonality to help make data stationary.

Testing stationarity before and after differencing helps prepare data for time series models.

Practice

(1/5)
1. What does it mean when a time series is stationary?
easy
A. It has missing values that need to be filled
B. It has a clear upward or downward trend
C. It contains seasonal patterns repeating over fixed intervals
D. Its statistical properties like mean and variance do not change over time

Solution

  1. Step 1: Understand stationarity definition

    Stationarity means the data's mean, variance, and other statistics stay constant over time.
  2. Step 2: Compare options to definition

    Only Its statistical properties like mean and variance do not change over time describes constant statistical properties; others describe trends, seasonality, or missing data.
  3. Final Answer:

    Its statistical properties like mean and variance do not change over time -> Option D
  4. Quick Check:

    Stationary = constant mean/variance [OK]
Hint: Stationary means stats don't change over time [OK]
Common Mistakes:
  • Confusing stationarity with trend presence
  • Thinking seasonality means stationarity
  • Assuming missing data affects stationarity
2. Which Python code correctly applies first-order differencing to a pandas Series data?
easy
A. data.dropna()
B. data.diff(1)
C. data.cumsum()
D. data.shift(1)

Solution

  1. Step 1: Recall differencing method in pandas

    The diff(1) method calculates the difference between current and previous values, performing first-order differencing.
  2. Step 2: Check other options

    shift(1) shifts data, cumsum() sums cumulatively, and dropna() removes missing values, none perform differencing.
  3. Final Answer:

    data.diff(1) -> Option B
  4. Quick Check:

    First difference = diff(1) [OK]
Hint: Use diff(1) for first-order differencing in pandas [OK]
Common Mistakes:
  • Using shift instead of diff for differencing
  • Confusing cumulative sum with differencing
  • Dropping NaNs instead of differencing
3. Given this code snippet:
import pandas as pd
series = pd.Series([10, 12, 15, 20, 25])
diff_series = series.diff(1).dropna()
print(diff_series.tolist())

What is the output?
medium
A. [0, 2, 3, 5, 5]
B. [10, 12, 15, 20, 25]
C. [2.0, 3.0, 5.0, 5.0]
D. [nan, 2, 3, 5, 5]

Solution

  1. Step 1: Calculate first differences

    Differences: 12-10=2, 15-12=3, 20-15=5, 25-20=5.
  2. Step 2: Drop NaN and print list

    The first difference is NaN, dropped by dropna(), so output is [2.0, 3.0, 5.0, 5.0].
  3. Final Answer:

    [2.0, 3.0, 5.0, 5.0] -> Option C
  4. Quick Check:

    Diff values = [2.0,3.0,5.0,5.0] [OK]
Hint: First diff drops first NaN, output is differences list [OK]
Common Mistakes:
  • Including NaN in output list
  • Printing original series instead of differences
  • Confusing shift with diff output
4. You applied first-order differencing to a time series but it still shows a trend. What is the likely issue?
medium
A. The series needs second-order differencing to remove the trend
B. You should use cumulative sum instead of differencing
C. The series is already stationary and differencing added noise
D. You forgot to normalize the data before differencing

Solution

  1. Step 1: Understand differencing orders

    First-order differencing removes linear trends; if trend remains, higher order differencing may be needed.
  2. Step 2: Evaluate other options

    Cumulative sum adds trend, normalization doesn't remove trend, and differencing adding noise means series was not stationary before.
  3. Final Answer:

    The series needs second-order differencing to remove the trend -> Option A
  4. Quick Check:

    Trend remains -> try second differencing [OK]
Hint: If trend remains, increase differencing order [OK]
Common Mistakes:
  • Using cumulative sum instead of differencing
  • Assuming normalization removes trend
  • Stopping at first differencing without checking stationarity
5. You have a monthly sales time series with a yearly seasonal pattern and an upward trend. Which differencing approach should you apply to make it stationary?
hard
A. Apply first-order differencing followed by seasonal differencing with lag 12
B. Apply only first-order differencing
C. Apply only seasonal differencing with lag 12
D. Apply logarithm transformation without differencing

Solution

  1. Step 1: Identify components to remove

    The series has both trend and yearly seasonality, so both need to be removed for stationarity.
  2. Step 2: Choose differencing methods

    First-order differencing removes trend; seasonal differencing with lag 12 removes yearly seasonality.
  3. Step 3: Combine differencing steps

    Applying first-order differencing then seasonal differencing is the correct approach to achieve stationarity.
  4. Final Answer:

    Apply first-order differencing followed by seasonal differencing with lag 12 -> Option A
  5. Quick Check:

    Trend + seasonality -> first + seasonal differencing [OK]
Hint: Remove trend then seasonality with two differencing steps [OK]
Common Mistakes:
  • Applying only one differencing type ignoring trend or seasonality
  • Using log transform alone to fix non-stationarity
  • Confusing seasonal lag with differencing order