简体   繁体   English

Pandas DataFrame 当 DatetimeIndex 是一年中的最后一天时重新采样到月份

[英]Pandas DataFrame Resample to Months when DatetimeIndex is last day of year

I've got a DataFrame with DatetimeIndex labeled as the last day of the year (ej 2020-12-31, 2021-12-31, etc).我有一个 DataFrame,其 DatetimeIndex 标记为一年中的最后一天(ej 2020-12-31、2021-12-31 等)。 I need to resample in order to expand the dataframe into months (ej 2020-01-31, 2020-02-29, etc).我需要重新采样以便将 dataframe 扩展到几个月(例如 2020-01-31、2020-02-29 等)。 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).当我使用重采样 function 时,它将始终从开始日期开始,而不是当年的第一天(ej 2020-12-31、2021-01-31)。

input:输入:

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

output: 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.使用.T将 dataframe 从列转置到行,使用freq 'm'date_range.min.max并再次用.T将 dataframe 从行转回到列。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM