- Data Analysis with Python
-
Overview
- Introduction to Data Science and Analytics
- Loading and Cleaning Data in Pandas
- Data Manipulation with NumPy and Pandas
- Exploratory Data Analysis (EDA) Techniques
- Handling Missing Data and Duplicates
- Merging, Joining, and Concatenating DataFrames
- Time Series Analysis Basics
- Data Visualization with Matplotlib and Seaborn
- Descriptive Statistics and Data Summarization
- Advanced Pandas Operations
Time Series Analysis Basics
Add to BookmarkIntroduction
Time series analysis is used to study data points collected over time. It helps in identifying trends, seasonal variations, and patterns in data. It is widely used in fields like finance, stock market analysis, weather forecasting, sales forecasting, and more.
In this tutorial, we will cover:
- What is Time Series Data?
- Working with Time Series Data in Pandas
- Resampling and Aggregation
- Rolling Statistics (Moving Average)
- Detecting Trends and Seasonality
- Time Series Forecasting Basics
1. What is Time Series Data?
Time series data is a sequence of observations recorded at time intervals (e.g., hourly, daily, weekly). Examples include:
- Stock prices recorded daily
- Monthly sales of a store
- Temperature readings every hour
2. Working with Time Series Data in Pandas
We use Pandas for handling time series data. Let's start by loading a dataset and converting a column into a DateTime index.
import pandas as pd
# Load dataset
data = pd.read_csv("sales_data.csv")
# Convert 'date' column to datetime format
data['date'] = pd.to_datetime(data['date'])
data.set_index('date', inplace=True)
# Display first few rows
print(data.head())
3. Resampling and Aggregation
Resampling helps in changing the frequency of time series data. For example, converting daily data into monthly data.
# Resampling to monthly data (sum of sales per month)
monthly_data = data.resample('M').sum()
print(monthly_data.head())
Common resampling options:
'D'
→ Daily'W'
→ Weekly'M'
→ Monthly'Y'
→ Yearly
4. Rolling Statistics (Moving Average)
Rolling mean (moving average) smooths fluctuations in time series data.
import matplotlib.pyplot as plt
# Compute 7-day moving average
data['7-day MA'] = data['sales'].rolling(window=7).mean()
# Plot original data and moving average
plt.figure(figsize=(10, 5))
plt.plot(data.index, data['sales'], label="Original Sales")
plt.plot(data.index, data['7-day MA'], label="7-Day Moving Avg", color='red')
plt.legend()
plt.show()
5. Detecting Trends and Seasonality
Using Seasonal Decomposition to analyze trends, seasonality, and residuals.
from statsmodels.tsa.seasonal import seasonal_decompose
# Decompose the time series
decomposition = seasonal_decompose(data['sales'], model='additive')
# Plot components
decomposition.plot()
plt.show()
6. Time Series Forecasting Basics
A basic forecasting technique is Exponential Smoothing:
from statsmodels.tsa.holtwinters import SimpleExpSmoothing
# Apply Simple Exponential Smoothing
model = SimpleExpSmoothing(data['sales']).fit(smoothing_level=0.2, optimized=False)
data['forecast'] = model.fittedvalues
# Plot the forecast
plt.figure(figsize=(10, 5))
plt.plot(data.index, data['sales'], label="Original Sales")
plt.plot(data.index, data['forecast'], label="Forecast", color='red')
plt.legend()
plt.show()
Conclusion
- Time series data is essential for forecasting and trend analysis.
- Pandas provides powerful tools for handling time series data (resampling, rolling mean, etc.).
- Seasonal decomposition helps identify trends and patterns.
- Forecasting techniques like exponential smoothing provide simple predictions.
Prepare for Interview
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- Python Challenging Programming Exercises Part 1
- Understanding Data Lake, Data Warehouse, Data Mart, and Data Lakehouse – And Why We Need Them
- Extract RGB Color From a Image Using CV2
- Deep Learning (DL): The Core of Modern AI
- Loan Default Prediction Project Using Machine Learning
- Internet of Things (IoT) & AI – Smart Devices and AI Working Together
- Store Data Into CSV File Using Python Tkinter GUI Library
- AI Agents & Autonomous Systems – The Future of Self-Driven Intelligence
- Important Mistakes to Avoid While Advertising on Facebook
- SQL Joins Explained: A Complete Guide with Examples
- Datasets for Speech Recognition Analysis
- Quantum AI – The Future of AI Powered by Quantum Computing
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- What is YII? and How to Install it?
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset