I've got a DataFrame with DatetimeIndex labeled as the last day of the year (ej 2020-12-31, 2021-12-31, etc). I need to resample in order to expand the dataframe into months (ej 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 (ej 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.