How to deal with missing values in a Timeseries in Python?
Last Updated :
26 Dec, 2023
It is common to come across missing values when working with real-world data. Time series data is different from traditional machine learning datasets because it is collected under varying conditions over time. As a result, different mechanisms can be responsible for missing records at different times. These mechanisms are known as missingness mechanisms. In this article, we will discuss how to handle missing values in time series data using Python.
What is Timeseries Data?
Time series is a sequence of observations recorded at regular time intervals. Time series analysis can be useful to see how a given asset, security, or economic variable changes over time. Another big question is why we need to deal with missing values in the dataset and why the missing values are present in the data.
- The handling of missing data is very important during the preprocessing of the dataset as many machine learning algorithms do not support missing values.
- Time series are subject to missing points due to problems in reading or recording the data.
Why can't we change the missing values with the global mean because the time series data might have some seasonality or trend?
Conventional methods such as mean and mode imputation, deletion, and other methods are not good enough to handle missing values as those methods can cause bias in the data. Estimation or imputation of the missing data with the values produced by some procedures or algorithms can be the best possible solution to minimize the bias effect of the conventional method of the data. So that at last, the data will be completed and ready to use for another step of analysis or data mining.
Types of Time Series Data
Let's start by categorizing time series data based on its composition before delving into imputation methods. If we use a linear regression model to break down the time series data, it can be represented as:
Y_{t}=m_{t}+s_{t}+\epsilon_{t}
Here,
- m_{t}
represents the trend,
- s_{t}
represents seasonality, and
- \epsilon_{t}
represents random variables.
Based on the presence or absence of these components, the passage identifies four types of time series data:
1. No trend or seasonality (Constant): Data remains relatively constant over time, with neither trend nor seasonal fluctuations.
Y_{t}=\epsilon_{t}
2. Trend, but no seasonality (Trendy): Data exhibits a clear long-term trend (increasing or decreasing) but no regular seasonal patterns.
Y_{t}=m_{t}+\epsilon_{t}
3. Seasonality, but no trend (Seasonal): Data shows recurring fluctuations within a specific period (e.g., monthly sales cycles) but no overall trend over time.
Y_{t}=s_{t}+\epsilon_{t}
4. Both trend and seasonality (Trend-seasonal): Data exhibits both a long-term trend and recurring seasonal patterns. This is the most complex type of time series data.
Y_{t}=m_{t}+s_{t}+\epsilon_{t}
Types of Missing Data
Missing data is a common challenge in time series analysis, impacting the accuracy and reliability of your results. Understanding the different types of missing data is crucial for choosing the right imputation strategy to address them effectively. Here's a breakdown of the main types:
- Missing Completely at Random (MCAR): Data points are missing randomly and independently of any other variables or observations. This is the ideal case for imputation, as any method can be used without introducing bias.
- Missing at Random (MAR): Data points are missing depending on observed values in other variables, but not on the missing values themselves. This is a more complex scenario, but imputation using observed data can still be effective.
- Missing Not at Random (MNAR): Data points are missing depending on the missing values themselves, making them difficult to predict accurately. This is the most challenging case, as traditional imputation methods can introduce bias and distort your analysis.
Handle Missing Values in Time Series in Python
Here's an step by step guide of Python implementation for handling missing values in a time series dataset:
Step 1: Importing the Libraries
Here we are importing all the necessary libraries:
Python3
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
Step 2: Importing the Dataset
- Importing data: It imports pandas library (pd) and reads the data from the CSV file using
pd.read_csv
, assuming the first row doesn't contain column names (header=None). - Naming columns: It assigns "Date" and "Customers" as names for the two columns using df.columns.
- Converting date format: It converts the "Date" column into a proper datetime format with year, month, and day order using
pd.to_datetime
and specifying the original format string (%Y-%m). - Setting Date index: It sets the "Date" column as the index of the DataFrame using
df.set_index
, making it the reference point for time-based operations. - Checking data shape and preview: It checks the final data shape with
df.shape
and displays the first few rows with df.head()
.
Python3
# import the data
df= pd.read_csv('/Time-Series.csv', header=None)
# name the columns
df.columns=['Date','Customers']
# represent date column in date fromat in the order, Year, month and the day
df['Date']=pd.to_datetime(df['Date'], format='%Y-%m')
# set the Date column be the index of our dataset
df= df.set_index('Date')
# now check the data shape
df.shape
print(df.head())
Output:
(144, 1)
Customers
Date
1949-01-01 114.0
1949-02-01 120.0
1949-03-01 134.0
1949-04-01 67.0
1949-05-01 123.0
- Identifying missing values:
nul_data = pd.isnull(df['Customers'])
: This line uses the pd.isnull
function from pandas to create a new Boolean Series (nul_data
) containing True
for every missing value in the "Customers" column of the DataFrame df
and False
otherwise.
- Filtering and printing data:
df[nul_data]
: This line uses Boolean indexing to filter the original DataFrame df
based on the nul_data
Series. It essentially selects only the rows where the "Customers" value is missing (i.e., True
in the corresponding nul_data
series).
Python3
nul_data = pd.isnull(df['Customers'])
# print only the data, Customers = NaN
df[nul_data]
Output:
Customers
Date
1951-06-01 NaN
1951-07-01 NaN
1954-06-01 NaN
1960-03-01 NaN
Plot the Graph
This creates a line plot of the data in the DataFrame df
. It automatically uses the index (assumed to be the date) as the x-axis and the "Customers" column as the y-axis.
Python3
plt.rcParams['figure.figsize']=(15,7)
# plots our series
plt.plot(df, color='green')
plt.title('Customers visted shop since 1950')
plt.show()
Output:

Step 3: Imputing the Missing Values
Here is the explanation of the techniques mentioned for handling missing values in time series data:
- Mean Imputation: Replaces missing values with the average of the entire column. Simple and fast, but may not capture trends or local variations.
- Median Imputation: Replaces missing values with the median of the entire column. Less sensitive to outliers than mean, but still lacks local context.
- Last Observation Carried Forward (LOCF): Replaces missing values with the last known value. Works well for data with rising or constant trends, but can distort trends if they change direction.
- Next Observation Carried Backward (NOCB): Replaces missing values with the next known value. Similar to LOCF but for downward trends. Both LOCF and NOCB can introduce artificial jumps or dips.
- Linear Interpolation: Estimates missing values by drawing a straight line between the two nearest known data points. Good for capturing linear trends, but less accurate for complex patterns.
- Spline Interpolation: Estimates missing values by fitting a flexible, curved line through the data points. More accurate for capturing complex trends and subtle changes than linear interpolation, but computationally more expensive.
1. Mean imputation
It performs mean imputation on the "Customers" column of the DataFrame. It creates a new column named "FillMean" containing the original values where available and the average value of the "Customers" column where missing.
Python3
plt.rcParams['figure.figsize']=(15,7)
# fill the missing data using the mean of the present observations
df = df.assign(FillMean=df.Customers.fillna(df.Customers.mean()))
# pass the data and declared the colour of your curve, i.e., blue
plt.plot(df, color='green')
plt.title('Mean Imputation')
plt.show()
Output:

2. Median imputation
It performs median imputation on the dataset. It copies all existing columns and adds a new column named FillMedian
. This new column fills in missing values in the Customers
column using the median value of that column (df.Customers.median()
).
Python3
plt.rcParams['figure.figsize']=(15,7)
# fill the missing data using the of the present observations
dataset = df.assign(FillMean=df.Customers.fillna(df.Customers.median()))
# pass the data and declared the colouyr opf our curve as blue
plt.plot(dataset, color='green')
plt.title('Median Imputation')
plt.show()
Output:

3. Last Observation Carried Forward(LOCF)
In this we are imputing missing values in time series data and visualizing the results using Last Observation Carried Forward (LOCF) technique imputes missing values in the "Customers" column by copying the previous values and then visualizes the resulting time series.
Python3
plt.rcParams['figure.figsize']=(15,7)
# On the customer column of our data, impute the missing values with the LOCF
df['Customers_locf']= df['Customers'].fillna(method ='bfill')
# plot our time series with imputed values
plt.plot(df['Customers_locf'], color='green')
plt.title('Last Observation Carried Forward')
plt.show()
Output:
.webp)
4. Next Observation Carried Backward(NOCB)
In this we are imputing missing values in time series data but uses a different technique: Next Observation Carried Backward (NOCB) imputation to fill missing values in the "Customers" column by copying the next available observation and then visualizes the time series data.
Python3
plt.rcParams['figure.figsize']=(15,7)
# On the customer column of our data, impute the missing values with the LOCF
df['Customers_nocb']= df['Customers'].fillna(method ='ffill')
# plot our time series with imputed values
plt.plot(df['Customers_nocb'], color='green')
plt.title('Next Observation Carried Backward')
plt.show()
Output:

3. Linear Interpolation
In this we are imputing missing values in time series data using a technique called linear interpolation to estimate and fill in missing values in the "Customers" column.
Python3
plt.rcParams['figure.figsize']=(15,7)
# on our data, impute the missing values using rolling window method
df['Customers_L']= df['Customers'].interpolate(method='linear')
# plot the complete dataset
plt.plot(df['Customers_L'], color='green')
plt.title('Linear interpolatoin')
plt.show()
Output:
.webp)
6. Spline Interpolation
In this we are imputing missing values in time series data using a technique called spline interpolation to estimate and fill in missing values in the "Customers" column.
Python3
plt.rcParams['figure.figsize']=(15,7)
# on our data, impute the missing values using the interpolation techniques and specifically, the lineare method
df['Customers_Spline']= df['Customers'].interpolate(option='spline')
# plot the complete dataset
plt.plot(df['Customers_Spline'], color='green')
plt.title('Spline Interpolation')
plt.show()
Output:

Conclusion
Dealing with missing values in your Python time series can be a frustrating experience. However, with careful analysis and the right imputation technique, you can transform fragmented data into a smooth and reliable flow for more accurate analysis. It's important to note that there is no one-size-fits-all approach to imputation, so it's essential to assess your data, understand the patterns of missingness, and choose the technique that best preserves the integrity and meaning of your time series. By embracing the power of imputation and bridging the gaps with confidence, you can take your time series analysis to new heights!
Similar Reads
Data Analysis with Python In this article, we will discuss how to do data analysis with Python. We will discuss all sorts of data analysis i.e. analyzing numerical data with NumPy, Tabular data with Pandas, data visualization Matplotlib, and Exploratory data analysis.Data Analysis With Python Data Analysis is the technique o
15+ min read
Introduction to Data Analysis
Data Analysis Libraries
Data Visulization Libraries
Matplotlib TutorialMatplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It
5 min read
Python Seaborn TutorialSeaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive.In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of
15+ min read
Plotly tutorialPlotly library in Python is an open-source library that can be used for data visualization and understanding data simply and easily. Plotly supports various types of plots like line charts, scatter plots, histograms, box plots, etc. So you all must be wondering why Plotly is over other visualization
15+ min read
Introduction to Bokeh in PythonBokeh is a Python interactive data visualization. Unlike Matplotlib and Seaborn, Bokeh renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Features of Bokeh: Some o
1 min read
Exploratory Data Analysis (EDA)
Univariate, Bivariate and Multivariate data and its analysisIn this article,we will be discussing univariate, bivariate, and multivariate data and their analysis. Univariate data: Univariate data refers to a type of data in which each observation or data point corresponds to a single variable. In other words, it involves the measurement or observation of a s
5 min read
Measures of Central Tendency in StatisticsCentral tendencies in statistics are numerical values that represent the middle or typical value of a dataset. Also known as averages, they provide a summary of the entire data, making it easier to understand the overall pattern or behavior. These values are useful because they capture the essence o
11 min read
Measures of Spread - Range, Variance, and Standard DeviationCollecting the data and representing it in form of tables, graphs, and other distributions is essential for us. But, it is also essential that we get a fair idea about how the data is distributed, how scattered it is, and what is the mean of the data. The measures of the mean are not enough to descr
8 min read
Interquartile Range and Quartile Deviation using NumPy and SciPyIn statistical analysis, understanding the spread or variability of a dataset is crucial for gaining insights into its distribution and characteristics. Two common measures used for quantifying this variability are the interquartile range (IQR) and quartile deviation. Quartiles Quartiles are a kind
5 min read
Anova FormulaANOVA Test, or Analysis of Variance, is a statistical method used to test the differences between the means of two or more groups. Developed by Ronald Fisher in the early 20th century, ANOVA helps determine whether there are any statistically significant differences between the means of three or mor
7 min read
Skewness of Statistical DataSkewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean. In simpler terms, it indicates whether the data is concentrated more on one side of the mean compared to the other side.Why is skewness important?Understanding the skewness of data
5 min read
How to Calculate Skewness and Kurtosis in Python?Skewness is a statistical term and it is a way to estimate or measure the shape of a distribution. Â It is an important statistical methodology that is used to estimate the asymmetrical behavior rather than computing frequency distribution. Skewness can be two types: Symmetrical: A distribution can b
3 min read
Difference Between Skewness and KurtosisWhat is Skewness? Skewness is an important statistical technique that helps to determine the asymmetrical behavior of the frequency distribution, or more precisely, the lack of symmetry of tails both left and right of the frequency curve. A distribution or dataset is symmetric if it looks the same t
4 min read
Histogram | Meaning, Example, Types and Steps to DrawWhat is Histogram?A histogram is a graphical representation of the frequency distribution of continuous series using rectangles. The x-axis of the graph represents the class interval, and the y-axis shows the various frequencies corresponding to different class intervals. A histogram is a two-dimens
5 min read
Interpretations of HistogramHistograms helps visualizing and comprehending the data distribution. The article aims to provide comprehensive overview of histogram and its interpretation. What is Histogram?Histograms are graphical representations of data distributions. They consist of bars, each representing the frequency or cou
7 min read
Box PlotBox Plot is a graphical method to visualize data distribution for gaining insights and making informed decisions. Box plot is a type of chart that depicts a group of numerical data through their quartiles. In this article, we are going to discuss components of a box plot, how to create a box plot, u
7 min read
Quantile Quantile plotsThe quantile-quantile( q-q plot) plot is a graphical method for determining if a dataset follows a certain probability distribution or whether two samples of data came from the same population or not. Q-Q plots are particularly useful for assessing whether a dataset is normally distributed or if it
8 min read
What is Univariate, Bivariate & Multivariate Analysis in Data Visualisation?Data Visualisation is a graphical representation of information and data. By using different visual elements such as charts, graphs, and maps data visualization tools provide us with an accessible way to find and understand hidden trends and patterns in data. In this article, we are going to see abo
3 min read
Using pandas crosstab to create a bar plotIn this article, we will discuss how to create a bar plot by using pandas crosstab in Python. First Lets us know more about the crosstab, It is a simple cross-tabulation of two or more variables. What is cross-tabulation? It is a simple cross-tabulation that help us to understand the relationship be
3 min read
Exploring Correlation in PythonThis article aims to give a better understanding of a very important technique of multivariate exploration. A correlation Matrix is basically a covariance matrix. Also known as the auto-covariance matrix, dispersion matrix, variance matrix, or variance-covariance matrix. It is a matrix in which the
4 min read
Covariance and CorrelationCovariance and correlation are the two key concepts in Statistics that help us analyze the relationship between two variables. Covariance measures how two variables change together, indicating whether they move in the same or opposite directions. Relationship between Independent and dependent variab
5 min read
Factor Analysis | Data AnalysisFactor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean i
13 min read
Data Mining - Cluster AnalysisData mining is the process of finding patterns, relationships and trends to gain useful insights from large datasets. It includes techniques like classification, regression, association rule mining and clustering. In this article, we will learn about clustering analysis in data mining.Understanding
6 min read
MANOVA Test in R ProgrammingMultivariate analysis of variance (MANOVA) is simply an ANOVA (Analysis of variance) with several dependent variables. It is a continuation of the ANOVA. In an ANOVA, we test for statistical differences on one continuous dependent variable by an independent grouping variable. The MANOVA continues th
4 min read
MANOVA Test in R ProgrammingMultivariate analysis of variance (MANOVA) is simply an ANOVA (Analysis of variance) with several dependent variables. It is a continuation of the ANOVA. In an ANOVA, we test for statistical differences on one continuous dependent variable by an independent grouping variable. The MANOVA continues th
4 min read
Python - Central Limit TheoremCentral Limit Theorem (CLT) is a foundational principle in statistics, and implementing it using Python can significantly enhance data analysis capabilities. Statistics is an important part of data science projects. We use statistical tools whenever we want to make any inference about the population
7 min read
Probability Distribution FunctionProbability Distribution refers to the function that gives the probability of all possible values of a random variable.It shows how the probabilities are assigned to the different possible values of the random variable.Common types of probability distributions Include: Binomial Distribution.Bernoull
8 min read
Probability Density Estimation & Maximum Likelihood EstimationProbability density and maximum likelihood estimation (MLE) are key ideas in statistics that help us make sense of data. Probability Density Function (PDF) tells us how likely different outcomes are for a continuous variable, while Maximum Likelihood Estimation helps us find the best-fitting model f
8 min read
Exponential Distribution in R Programming - dexp(), pexp(), qexp(), and rexp() FunctionsThe Exponential Distribution is a continuous probability distribution that models the time between independent events occurring at a constant average rate. It is widely used in fields like reliability analysis, queuing theory, and survival analysis. The exponential distribution is a special case of
5 min read
Binomial Distribution in Data ScienceBinomial Distribution is used to calculate the probability of a specific number of successes in a fixed number of independent trials where each trial results in one of two outcomes: success or failure. It is used in various fields such as quality control, election predictions and medical tests to ma
7 min read
Poisson Distribution | Definition, Formula, Table and ExamplesThe Poisson distribution is a discrete probability distribution that calculates the likelihood of a certain number of events happening in a fixed time or space, assuming the events occur independently and at a constant rate.It is characterized by a single parameter, λ (lambda), which represents the
11 min read
P-Value: Comprehensive Guide to Understand, Apply, and InterpretA p-value is a statistical metric used to assess a hypothesis by comparing it with observed data. This article delves into the concept of p-value, its calculation, interpretation, and significance. It also explores the factors that influence p-value and highlights its limitations. Table of Content W
12 min read
Z-Score in Statistics | Definition, Formula, Calculation and UsesZ-Score in statistics is a measurement of how many standard deviations away a data point is from the mean of a distribution. A z-score of 0 indicates that the data point's score is the same as the mean score. A positive z-score indicates that the data point is above average, while a negative z-score
15+ min read
How to Calculate Point Estimates in R?Point estimation is a technique used to find the estimate or approximate value of population parameters from a given data sample of the population. The point estimate is calculated for the following two measuring parameters:Measuring parameterPopulation ParameterPoint EstimateProportionÏp MeanμxÌ Th
3 min read
Confidence IntervalA Confidence Interval (CI) is a range of values that contains the true value of something we are trying to measure like the average height of students or average income of a population.Instead of saying: âThe average height is 165 cm.âWe can say: âWe are 95% confident the average height is between 1
7 min read
Chi-square test in Machine LearningChi-Square test helps us determine if there is a significant relationship between two categorical variables and the target variable. It is a non-parametric statistical test meaning it doesnât follow normal distribution. Example of Chi-square testThe Chi-square test compares the observed frequencies
7 min read
Hypothesis TestingHypothesis testing compares two opposite ideas about a group of people or things and uses data from a small part of that group (a sample) to decide which idea is more likely true. We collect and study the sample data to check if the claim is correct.Hypothesis TestingFor example, if a company says i
9 min read
Data Preprocessing
Data Transformation
Time Series Data Analysis
Data Mining - Time-Series, Symbolic and Biological Sequences DataData mining refers to extracting or mining knowledge from large amounts of data. In other words, Data mining is the science, art, and technology of discovering large and complex bodies of data in order to discover useful patterns. Theoreticians and practitioners are continually seeking improved tech
3 min read
Basic DateTime Operations in PythonPython has an in-built module named DateTime to deal with dates and times in numerous ways. In this article, we are going to see basic DateTime operations in Python. There are six main object classes with their respective components in the datetime module mentioned below: datetime.datedatetime.timed
12 min read
Time Series Analysis & Visualization in PythonTime series data consists of sequential data points recorded over time which is used in industries like finance, pharmaceuticals, social media and research. Analyzing and visualizing this data helps us to find trends and seasonal patterns for forecasting and decision-making. In this article, we will
6 min read
How to deal with missing values in a Timeseries in Python?It is common to come across missing values when working with real-world data. Time series data is different from traditional machine learning datasets because it is collected under varying conditions over time. As a result, different mechanisms can be responsible for missing records at different tim
9 min read
How to calculate MOVING AVERAGE in a Pandas DataFrame?Calculating the moving average in a Pandas DataFrame is used for smoothing time series data and identifying trends. The moving average, also known as the rolling mean, helps reduce noise and highlight significant patterns by averaging data points over a specific window. In Pandas, this can be achiev
7 min read
What is a trend in time series?Time series data is a sequence of data points that measure some variable over ordered period of time. It is the fastest-growing category of databases as it is widely used in a variety of industries to understand and forecast data patterns. So while preparing this time series data for modeling it's i
3 min read
How to Perform an Augmented Dickey-Fuller Test in RAugmented Dickey-Fuller Test: It is a common test in statistics and is used to check whether a given time series is at rest. A given time series can be called stationary or at rest if it doesn't have any trend and depicts a constant variance over time and follows autocorrelation structure over a per
3 min read
AutoCorrelationAutocorrelation is a fundamental concept in time series analysis. Autocorrelation is a statistical concept that assesses the degree of correlation between the values of variable at different time points. The article aims to discuss the fundamentals and working of Autocorrelation. Table of Content Wh
10 min read
Case Studies and Projects