且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用自定义期间进行重新采样

更新时间:2023-02-13 12:48:59

如果使用numpy 1.7,则可以使用datetime64& timedelta64数组进行计算:

If you use numpy 1.7, you can use datetime64 & timedelta64 arrays to do the calculation:

创建示例数据:

import pandas as pd
import numpy as np

begin = pd.datetime(2013,1,1)
end = pd.datetime(2013,2,20)

dtrange = pd.date_range(begin, end)

p1 = np.random.rand(len(dtrange)) + 5
p2 = np.random.rand(len(dtrange)) + 10

df = pd.DataFrame({'p1': p1, 'p2': p2}, index=dtrange)

计算dekad的日期:

calculate the dekad's date:

d = df.index.day - np.clip((df.index.day-1) // 10, 0, 2)*10 - 1
date = df.index.values - np.array(d, dtype="timedelta64[D]")
df.groupby(date).mean()

输出为:

                 p1         p2
2013-01-01  5.413795  10.445640
2013-01-11  5.516063  10.491339
2013-01-21  5.539676  10.528745
2013-02-01  5.783467  10.478001
2013-02-11  5.358787  10.579149