Pandas 如何编写一个函数,从熊猫的每日数据中获取每月、每周的数据?

Pandas 如何编写一个函数,从熊猫的每日数据中获取每月、每周的数据?,pandas,Pandas,我有一个数据框,如下所示,我需要编写一个函数,根据输入参数将此数据转换为每周(星期日为周末日期)或每月:- 每日价格df数据示例: date price_chair vol_glass 02-09-2018 2 6 03-09-2018 1 5 04-09-2018 3 6 05-09-2018 4

我有一个数据框,如下所示,我需要编写一个函数,根据输入参数将此数据转换为每周(星期日为周末日期)或每月:-

每日价格df数据示例:

date             price_chair     vol_glass
02-09-2018         2              6
03-09-2018         1              5
04-09-2018         3              6
05-09-2018         4              8
10-09-2018         5              10
15-09-2018         2              10
18-09-2018         2              10
01-10-2018         3              20
如果选项为每月,则取一个月的平均价格和玻璃体积之和,这些列可能有所不同:

year_month        price_chair_avg_monthly     vol_glass_sum_monthly
2018-09            2.71                    55
2018-10            3                       20
date    price_chair_avg_weekly  vol_glass_sum_weekly
02/09/18    2                    6
09/09/18    2.67                 19
16/09/18    3.5                  20
23/09/18    2                    10
30/09/18        
07/10/18    3                    20
如果选项为每周,则取一周的平均价格和玻璃体积之和,这些列可能有所不同:

year_month        price_chair_avg_monthly     vol_glass_sum_monthly
2018-09            2.71                    55
2018-10            3                       20
date    price_chair_avg_weekly  vol_glass_sum_weekly
02/09/18    2                    6
09/09/18    2.67                 19
16/09/18    3.5                  20
23/09/18    2                    10
30/09/18        
07/10/18    3                    20
与字典一起使用以指定列和重采样函数:

#if first column is not index
#df = df.set_index('date')

df.index = pd.to_datetime(df.index, dayfirst=True)

df1 = df.resample('MS').agg({'price_chair':'mean','vol_glass':'sum'})
print (df1)
            price_chair  vol_glass
date                              
2018-09-01     2.714286         55
2018-10-01     3.000000         20

df2 = df.resample('W').agg({'price_chair':'mean','vol_glass':'sum'})
print (df2)
            price_chair  vol_glass
date                              
2018-09-02     2.000000          6
2018-09-09     2.666667         19
2018-09-16     3.500000         20
2018-09-23     2.000000         10
2018-09-30          NaN          0
2018-10-07     3.000000         20

嗨,耶斯雷尔,再次感谢你!你知道在美国每两周选什么吗case@user3222101-然后将
W
更改为
2W
@user322101-我看到了你的新问题-你能从我的答案和预期输出中添加此代码吗?那么就没有理由投反对票了。谢谢你,耶斯雷尔,我已经在那里加上了我正在努力解决的问题。再次感谢