-1

I've got a DataFrame with DatetimeIndex labeled as the last day of the year (e.j. 2020-12-31, 2021-12-31, etc). I need to resample in order to expand the dataframe into months (e.j. 2020-01-31, 2020-02-29, etc). When I use the resample function it will always start from the begining date, not the first day of that year (e.j 2020-12-31, 2021-01-31).

input:

         0          1          2      
Date 2020-12-31 2021-12-31 2022-12-31

output:

Out[122]: 
     0          1          2          3          4          5      ...     6
Date 2020-01-31 2020-02-28 2020-03-31 2020-04-30 2020-05-31 2020-06-30 ... 2022-12-31

Thanks.

David Erickson
  • 16,433
  • 2
  • 19
  • 35

1 Answers1

0

Transpose the dataframe from columns to rows with .T, get the date_range from the .min to the .max with a freq of 'm' and transpose the dataframe back from rows to columns with .T again.

from datetime import timedelta
df = pd.DataFrame({0 : ['2020-12-31'],
                 1 : ['2021-12-31'],
                 2 : ['2022-12-31']})
df = df.T
df[0] = pd.to_datetime(df[0])
df = pd.DataFrame({'Date' : pd.date_range(df[0].min()-timedelta(days=365), df[0].max(), freq='m').to_list()}).T
df

Out[122]: 
         0          1          2          3          4          5      ...     6
Date 2020-01-31 2020-02-28 2020-03-31 2020-04-30 2020-05-31 2020-06-30 ... 2022-12-31
David Erickson
  • 16,433
  • 2
  • 19
  • 35