通过在日期之间均匀分布将每月值更改为每天 [英] Changing monthly values to daily by evenly distributing between dates

查看:47
本文介绍了通过在日期之间均匀分布将每月值更改为每天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有每月数据集

df = pd.DataFrame({'Month':[1,2],
                   'Plan':[310,620],
                'Month_start_date': ['2020-01-01','2020-02-01']})
print(df)

df['Month_start_date'] = (pd.to_datetime(df['Month_start_date'], format='%Y/%m/%d')
                     .dt.to_period('m').dt.to_timestamp())

df = df.set_index('Month_start_date')

我以我想要重新索引的格式创建了一个日期列表

I created a list of dates in a format i would like to reindex

start = '2020-01-01'
end = '2020-02-29'
dates = pd.date_range(start, end, freq='D')
dates

当我尝试使用此代码将数据框更改为每日时

when i try to change the dataframe to daily using this code

df_daily = df.reindex(dates, method='ffill')
print(df_daily)

这是我得到的输出

           Month  Plan
2020-01-01      1   310
2020-01-02      1   310
2020-01-03      1   310
2020-01-04      1   310
2020-01-05      1   310
2020-01-06      1   310
2020-01-07      1   310
2020-01-08      1   310
2020-01-09      1   310
2020-01-10      1   310
...

该列表按预期持续到 2 月 29 日.然而,每天的计划保持不变.我怎样才能让它看起来像这样?

The list goes on till Feb 29th as expected. However plan remains same for everyday. How can i make it look like this?

            Month  Plan
2020-01-01      1   10
2020-01-02      1   10
2020-01-03      1   10
2020-01-04      1   10
2020-01-05      1   10
2020-01-06      1   10
2020-01-07      1   10
2020-01-08      1   10
2020-01-09      1   10
2020-01-10      1   10
...

2020-02-17      2   21.38
2020-02-18      2   21.38
2020-02-19      2   21.38
2020-02-20      2   21.38
2020-02-21      2   21.38
2020-02-22      2   21.38
2020-02-23      2   21.38
2020-02-24      2   21.38
2020-02-25      2   21.38
2020-02-26      2   21.38
2020-02-27      2   21.38
2020-02-28      2   21.38
2020-02-29      2   21.38

只需将计划除以当月的天数,将其平均划分为所有日期.由于二月的计划是 620,所以每天得到 620/29,即 21.38

Just divide the plan between all the dates evenly by dividing it by number of days in the month. Since the Feb has 620 as its plan, every day gets 620/29 which is 21.38

推荐答案

Pandas 有一个用于 一个月中的天数:

Pandas has a function for the number of days in a month:

df_daily["Daily plan"] = df_daily["Plan"] / df_daily.index.daysinmonth

这篇关于通过在日期之间均匀分布将每月值更改为每天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆