w3resource

Upsampling Time Series data from daily to Hourly Frequency

Pandas Resampling and Frequency Conversion: Exercise-2 with Solution

Write a Pandas program to upsample daily time series data to hourly frequency.

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-05', freq='D')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)

# Upsample the time series to hourly frequency
ts_hourly = ts.resample('H').ffill()

# Display the upsampled time series
print(ts_hourly)

Output:

2021-01-01 00:00:00    0.171632
2021-01-01 01:00:00    0.171632
2021-01-01 02:00:00    0.171632
2021-01-01 03:00:00    0.171632
2021-01-01 04:00:00    0.171632
  
2021-01-04 20:00:00    3.045198
2021-01-04 21:00:00    3.045198
2021-01-04 22:00:00    3.045198
2021-01-04 23:00:00    3.045198
2021-01-05 00:00:00   -1.323064
Freq: H, Length: 97, 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.
  • Upsample the time series data to hourly frequency by forward filling the values.
  • Print the upsampled time series data.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Resampling Time Series data to daily Frequency.
Next: Resampling Time Series data with different Aggregation methods.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/upsampling-time-series-data-from-daily-to-hourly-frequency.php