Time series analysis helps us understand data that changes over time. It shows patterns like trends and cycles to make better decisions.
0
0
Time series analysis patterns in Pandas
Introduction
Tracking daily sales to see if business is growing
Monitoring temperature changes over months
Checking website visitors hour by hour
Analyzing stock prices to find trends
Observing heart rate data during exercise
Syntax
Pandas
import pandas as pd # Load time series data with a datetime index series = pd.Series(data, index=pd.to_datetime(dates)) # Common pattern checks series.plot() # Visualize data series.rolling(window=3).mean() # Moving average to smooth data series.diff() # Differences to find changes series.autocorr(lag=1) # Correlation with lagged data
Time series data must have a datetime index for proper analysis.
Rolling windows help smooth short-term fluctuations to see trends.
Examples
This example creates a simple daily time series and plots it to see the pattern.
Pandas
import pandas as pd import matplotlib.pyplot as plt dates = pd.date_range('2024-01-01', periods=6) data = [10, 12, 15, 14, 13, 16] series = pd.Series(data, index=dates) # Plot the time series title = 'Daily values' series.plot(title=title) plt.show()
Calculates the 3-day moving average to smooth the data and highlight trends.
Pandas
rolling_avg = series.rolling(window=3).mean() print(rolling_avg)
Finds the difference between each day and the previous day to see changes.
Pandas
diffs = series.diff()
print(diffs)Measures how much today's value relates to yesterday's value.
Pandas
autocorr_value = series.autocorr(lag=1) print(f'Autocorrelation with lag 1: {autocorr_value}')
Sample Program
This program creates a time series, plots it, calculates a moving average to smooth the data, finds daily changes, and measures autocorrelation to see how values relate over time.
Pandas
import pandas as pd import matplotlib.pyplot as plt # Create sample time series data dates = pd.date_range('2024-01-01', periods=10) data = [5, 7, 6, 8, 10, 9, 11, 13, 12, 14] series = pd.Series(data, index=dates) # Plot original data series.plot(title='Original Time Series') plt.show() # Calculate 3-day moving average moving_avg = series.rolling(window=3).mean() print('3-day Moving Average:') print(moving_avg) # Calculate daily differences diffs = series.diff() print('\nDaily Differences:') print(diffs) # Calculate autocorrelation with lag 1 autocorr = series.autocorr(lag=1) print(f'\nAutocorrelation (lag=1): {autocorr:.2f}')
OutputSuccess
Important Notes
Missing values can appear in rolling averages at the start because there is not enough data to fill the window.
Autocorrelation helps detect repeating patterns or trends in time series.
Plotting is a great first step to visually understand your time series data.
Summary
Time series patterns show how data changes over time.
Use rolling averages to smooth data and see trends.
Differences and autocorrelation reveal changes and relationships in time.