Calculating Percentage change in Resampled data
Pandas Resampling and Frequency Conversion: Exercise-15 with Solution
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.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/pandas/resampling-frequency-conversion/calculating-percentage-change-in-resampled-time-series-data.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics