[英]Pandas forward fill proportionally
I have a dataframe like this: 我有一个这样的数据框:
Month/Year Value
01/2018 100
03/2018 200
06/2018 800
The values for 02/2018, 04/2018 and 05/2018 is missing because the value did not change in those months. 缺少02 / 2018、04 / 2018和05/2018的值,因为这些月份的值没有变化。 I would like to have a dataframe which incudes the missing months and values are increased proportionally:
我想有一个数据框,它会导致缺少的月份,并且值按比例增加:
Month/Year Value
01/2018 100
02/2018 150
03/2018 200
04/2018 400
04/2018 600
06/2018 800
Thank you for help with the solution! 感谢您提供解决方案的帮助!
First convert column to DatetimeIndex
, add missing datetimes by asfreq
, interpolate
and if necessary same format add strftime
: 首先将列转换为
DatetimeIndex
,通过asfreq
添加缺少的日期asfreq
,进行interpolate
并在必要时添加strftime
相同的格式:
df['Month/Year'] = pd.to_datetime(df['Month/Year'], format='%m/%Y')
df = df.set_index('Month/Year').asfreq('MS').interpolate().reset_index()
df['Month/Year'] = df['Month/Year'].dt.strftime('%m/%Y')
print (df)
Month/Year Value
0 01/2018 100.0
1 02/2018 150.0
2 03/2018 200.0
3 04/2018 400.0
4 05/2018 600.0
5 06/2018 800.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.