- 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
Introduction
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
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- How to Start Your Career as a DevOps Engineer
- Google’s Core Update in May 2020: What You Need to Know
- Datasets for analyze in Tableau
- Python Challenging Programming Exercises Part 3
- The Ultimate Guide to Data Science: Everything You Need to Know
- Loan Default Prediction Project Using Machine Learning
- Best Platform to Learn Digital Marketing in Free
- SQL Joins Explained: A Complete Guide with Examples
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- 15 Amazing Keyword Research Tools You Should Explore
- Big Data: The Future of Data-Driven Decision Making
- What is YII? and How to Install it?
- 10 Awesome Data Science Blogs To Check Out
- Important Mistakes to Avoid While Advertising on Facebook
- Datasets for Speech Recognition Analysis
Datasets for Machine Learning
- 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
- Bitcoin Heist Ransomware Address Dataset