简体   繁体   English

每天重新采样一次,以“月底减去t天”为单位在熊猫中进行补偿

[英]Resampling daily to monthly with 'month-end minus t days' offset in pandas

I have daily timeseries data in a pandas dataframe. 我在pandas数据框中有每日时间序列数据。 I need to resample this to monthly using different offsets from a standard month-end frequency. 我需要使用与标准月末频率不同的偏移量将其重新采样为每月一次。

dates = pd.date_range('2016-09-01', '2017-01-10')
df = pd.DataFrame(data=[x for x in range(len(dates))],index=dates,columns=['MyData'])

I can get to a monthly series with month end frequency: 我可以查看每月结束频率的每月系列:

df_monthly = df.resample('M').last()

df_monthly
Out[78]: 
            MyData
2016-09-30      29
2016-10-31      60
2016-11-30      90
2016-12-31     121
2017-01-31     131

If Month End = 'M', I would like to have similar monthly slices for 'M-15', ...'M-2', 'M-1', 'M', 'M+1', M+2', ...'M+15'. 如果Month End ='M',我想对'M-15',...'M-2','M-1','M','M + 1',M + 2',...'M + 15'。 Ultimately I plan to combine these into a single dataframe with column names 'M+T'. 最终,我计划将它们组合成列名称为“ M + T”的单个数据框。

Is there an easy way to do this within pd.DataFrame.resample() or pd.DataFrame.asfreq()? 在pd.DataFrame.resample()或pd.DataFrame.asfreq()中是否有一种简便的方法?

So as per the several ways you asked here is how it is done. 因此,根据您在此处询问的几种方式,它是如何完成的。

import pandas as pd
dates = pd.date_range('2016-09-01', '2017-01-10')
df = pd.DataFrame(data=[x for x in range(len(dates))],index=dates,columns=['MyData'])

df_monthly_m1 = df.shift(-1).resample('M').last()
df_monthly_m1

            MyData
2016-09-30    30.0
2016-10-31    61.0
2016-11-30    91.0
2016-12-31   122.0
2017-01-31   131.0

df_monthly_p1 = df.shift(1).resample('M').last()
df_monthly_p1

            MyData
2016-09-30    28.0
2016-10-31    59.0
2016-11-30    89.0
2016-12-31   120.0
2017-01-31   130.0

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

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