Calculating Percentage change in Resampled data
15. Calculate Percentage Change in Resampled Data
Write a Pandas program to calculate percentage change in Resampled data.
Sample Solution:
Python Code :
# Import necessary libraries
import pandas as pd
import numpy as np
# Create a time series data with daily frequency
date_rng = pd.date_range(start='2021-01-01', end='2021-01-10', freq='D')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)
# Resample the time series to daily frequency
ts_daily = ts.resample('D').mean()
# Calculate the percentage change in the resampled data
ts_pct_change = ts_daily.pct_change()
# Display the percentage change in the resampled time series
print(ts_pct_change)
Output:
2021-01-01 NaN 2021-01-02 -4.219191 2021-01-03 -0.483793 2021-01-04 1.751098 2021-01-05 0.088296 2021-01-06 -2.842570 2021-01-07 -1.521794 2021-01-08 -1.391348 2021-01-09 -4.379459 2021-01-10 -1.437542 Freq: D, dtype: float64
Explanation:
- Import Pandas and NumPy libraries.
- Create a date range with daily frequency.
- Generate a random time series data with the created date range.
- Resample the time series data to daily frequency by calculating the mean.
- Calculate the percentage change in the resampled data.
- Print the percentage change in the resampled time series data.
For more Practice: Solve these Related Problems:
- Write a Pandas program to resample a time series to monthly frequency and calculate the month-over-month percentage change.
- Write a Pandas program to compute the percentage change in resampled quarterly data and then visualize the trend using a line plot.
- Write a Pandas program to calculate the percentage change of yearly resampled data and compare it with the absolute differences.
- Write a Pandas program to resample a financial time series to daily frequency and then compute the rolling percentage change over a specified window.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Creating Custom Resampling periods.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.