Ask Your Question
2

How can pandas resample a daily time series to a monthly time series and retrieve the first available value of each month?

asked 2023-05-20 23:57:01 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-21 00:08:02 +0000

huitzilopochtli gravatar image

To resample a daily time series to a monthly time series and retrieve the first available value of each month, you can use the pandas resample() function along with the agg() function to apply the first() method to each group of monthly values:

import pandas as pd

# Create a sample daily time series
dates = pd.date_range(start='2021-01-01', end='2021-12-31', freq='D')
values = range(365)
df = pd.DataFrame({'date': dates, 'value': values})
df.set_index('date', inplace=True)

# Resample to monthly and retrieve first value
monthly = df.resample('M').agg({'value': 'first'})

In this example, the resample() function is called with the argument 'M', which indicates that we want to resample the time series to months. The agg() function is then called with a dictionary that specifies the column to aggregate ('value') and the method to use ('first').

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-20 23:57:01 +0000

Seen: 11 times

Last updated: May 21 '23