0

I want to get a monthly observation data from the daily data in pandas. That means, I want to get the data at every 5th day of the month (2011-01-05; 2011-02-05; 2011-03-05...2011-12-05) or the closest trading day to that date (e.g if 03-05 is not existed, it will search 2011-03-06). How can i do that?

The dataframe looks something like:

Date           Close
2011-01-01     100.99
2011-01-02     100.65
......
2011-12-31     76.08

1 Answer 1

1

Below answer will solve your problem but there is a caveat that there should be atleast a single day data for each month!

df['Date'] = pd.to_datetime(df['Date'])
df['day'] = df.Date.dt.day
df['month'] = df.Date.dt.month
df['year'] = df.Date.dt.year

def get_nearest_time_data(df, day):
    newdf = pd.DataFrame()
    for month in range(1,13):
        daydf = df[(df.day==day) & (df.month==month)]
        while (daydf.shape[0]==0):
            day+=1
            daydf = df[(df.day==day) & (df.month==month)]  
        newdf = pd.concat([newdf,daydf], ignore_index=True)
    return newdf

get_nearest_time_data(df, 5)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.