将月份的数量平均分配到几周 [英] Distribute month's quantity equally into weeks

查看:78
本文介绍了将月份的数量平均分配到几周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有两个数据帧:

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

解决方案

通过 解决方案

Convert datetimes to month period by to_period in both df.

Then created Series for map column Week and divide by length of each period created by 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

Details:

print (a.map(s))
0    100
1    100
2    100
3    100
4    100
5    200
6    200
7    200
8    200
Name: Week, dtype: int64

print (df2.index.to_series().groupby(a).transform('size'))
0    5
1    5
2    5
3    5
4    5
5    4
6    4
7    4
8    4
dtype: int64

这篇关于将月份的数量平均分配到几周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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