将月份的数量平均分配到数周

时间:2017-10-05 06:27:26

标签: pandas

有两个数据框:

1)df

    Month           Qty
    -------------------
0   2017-10-31      100 
1   2017-11-30      200 

2)周

    Week
    ----------
0   2017-10-01 
1   2017-10-08 
2   2017-10-15 
3   2017-10-22 
4   2017-10-29 
5   2017-11-05 
6   2017-11-12 
7   2017-11-19 
8   2017-11-26 

如何在几周内平均分配月份数量以获得以下输出:

    Week            Qty
    -------------------
0   2017-10-01      20
1   2017-10-08      20
2   2017-10-15      20
3   2017-10-22      20
4   2017-10-29      20
5   2017-11-05      50
6   2017-11-12      50
7   2017-11-19      50
8   2017-11-26      50

1 个答案:

答案 0 :(得分:0)

map info中将datetimes转换为month句号{。}}。

然后为地图列df创建Series并除以Week创建的每个句点的长度:

transform

详细说明:

df1['Month'] = pd.to_datetime(df1['Month']).dt.to_period('m')
df2['Week'] = pd.to_datetime(df2['Week'])

s = df1.set_index('Month')['Qty']
a = df2['Week'].dt.to_period('m')
df2['Qty'] = a.map(s) / df2.index.to_series().groupby(a).transform('size')
print (df2)
        Week   Qty
0 2017-10-01  20.0
1 2017-10-08  20.0
2 2017-10-15  20.0
3 2017-10-22  20.0
4 2017-10-29  20.0
5 2017-11-05  50.0
6 2017-11-12  50.0
7 2017-11-19  50.0
8 2017-11-26  50.0