How to Resample Time Series Data in Python?

Estimated read time 2 min read

To resample time series data in Python, you can use the resample() method provided by the pandas library. The resample() method allows you to change the frequency of your time series data by upsampling (increasing frequency) or downsampling (decreasing frequency). Here’s an example:

import pandas as pd

# Create a sample DataFrame with time series data
data = {'date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'],
        'value': [10, 20, 15, 25, 30]}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)

# Resample the data to a daily frequency
daily_resampled = df.resample('D').asfreq()

# Resample the data to a monthly frequency, taking the average value
monthly_resampled = df.resample('M').mean()

In this example, we start with a DataFrame df containing time series data with two columns: date and value. We convert the date column to a datetime type and set it as the index of the DataFrame using set_index().

To resample the data to a different frequency, we use the resample() method. In the first resampling operation, we resample the data to a daily frequency using 'D' as the frequency argument. The asfreq() function is used to retain the existing data points without any interpolation.

In the second resampling operation, we resample the data to a monthly frequency using 'M' as the frequency argument. We use the mean() function to calculate the average value for each month.

You can specify other frequencies for resampling, such as hourly ('H'), weekly ('W'), quarterly ('Q'), etc. Additionally, you can choose different resampling methods, such as taking the sum, minimum, maximum, or applying custom functions, depending on your specific requirements.

Pandas provides various options for resampling time series data, including downsampling with aggregation, upsampling with interpolation, and handling missing data. Refer to the pandas documentation for more details on the resample() method and its options:

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply