如何创建一个函数将大熊猫数据框中的每月数据转换为每日,每周?

时间:2018-10-01 06:09:36

标签: pandas

我在数据框中具有以下每月数据,我需要将数据转换为每周,每天,每两周一次。

[50.0, 6.0] 

预期输出: 每天:

date              chair_price     vol_chair
01-09-2018         23              30
01-10-2018         53              20

daily: price as same and vol_chair divided by days of the month
weekly: price as same and vol_chair divided by number of weeks in a month

每周:

   date              chair_price     vol_chair
01-09-2018            23               1
02-09-2018            23               1
03-09-2018            23               1
..
30-09-2018            23               1
01-10-2018            53               0.64
..
31-10-2018            53               0.64

我正在使用下面的代码作为列vol的任何快速组合方法,即保持价格不变和vol-采取行动并找出一个月中的星期数

     date              chair_price     vol_chair
02-09-2018               23              6
09-09-2018               23              6 
16-09-2018               23              6   
23-09-2018               23              6 
30-09-2018               23              6
07-10-2018               53              5
14-10-2018               53              5
..

1 个答案:

答案 0 :(得分:1)

使用:

#convert to datetimeindex
df.index = pd.to_datetime(df.index, dayfirst=True)

#add new next month for correct resample
idx = df.index[-1] + pd.offsets.MonthBegin(1)

df = df.append(df.iloc[[-1]].rename({df.index[-1]: idx}))

#resample with forward filling values, remove last helper row
#df1 = df.resample('D').ffill().iloc[:-1]
df1 = df.resample('W').ffill().iloc[:-1]

#divide by size of months
df1['vol_chair'] /= df1.resample('MS')['vol_chair'].transform('size')
print (df1)

            chair_price  vol_chair
date                              
2018-09-02           23        6.0
2018-09-09           23        6.0
2018-09-16           23        6.0
2018-09-23           23        6.0
2018-09-30           23        6.0
2018-10-07           53        5.0
2018-10-14           53        5.0
2018-10-21           53        5.0
2018-10-28           53        5.0