使用日期范围将月末数据转换为熊猫的每周数据

非线性

我有一个看起来像下面的数据框。是月末数据。

date ,     value , expectation
31/01/2020, 34,     40
28/02/2020, 35,     38
31/03/2020, 40,     44

我需要的:

date ,     value , expectation

07/01/2020, 0,       0 
14/01/2020, 0,       0
21/01/2020, 0,       0
28/01/2020, 0,       0 
04/02/2020, 34,     40
11/02/2020, 0,       0
18/02/2020, 0,       0
25/02/2020, 0,       0
04/03/2020, 35,     38

基本上,我正在尝试将月末数据转换为每周数据。但是,不同之处在于确切的月结束日期可能与每周的日期范围不匹配,因此它将落入星期结束日期(例如,2020年1月31日为04/02/2020)。另一个周末日期用0填充。听起来很乱。但这是我尝试过的。

import pandas as pd

df = pd.read_csv('file.csv', index_col=0)
df.index = pd.to_datetime(df.index, format='%d/%m/%y')

dtr = pd.date_range('01.01.2020', '31.03.2020', freq='W')

empty = pd.DataFrame(index=dtr)

df = pd.concat([df, empty[~empty.index.isin(df.index)]]).sort_index().fillna(0)

该代码有效,但是我没有得到确切的预期输出。任何帮助表示赞赏。

耶斯列尔

用途merge_asof

df.index = pd.to_datetime(df.index, format='%d/%m/%Y')

dtr = pd.date_range('01.01.2020', '31.03.2020', freq='W')
empty = pd.DataFrame(index=dtr)


df = pd.merge_asof(empty, 
                   df, 
                   left_index=True, 
                   right_index=True, 
                   tolerance=pd.Timedelta(7, 'd')).fillna(0)
print (df)
            value  expectation
2020-01-05    0.0          0.0
2020-01-12    0.0          0.0
2020-01-19    0.0          0.0
2020-01-26    0.0          0.0
2020-02-02   34.0         40.0
2020-02-09    0.0          0.0
2020-02-16    0.0          0.0
2020-02-23    0.0          0.0
2020-03-01   35.0         38.0
2020-03-08    0.0          0.0
2020-03-15    0.0          0.0
2020-03-22    0.0          0.0
2020-03-29    0.0          0.0

如果需要也随之变化开始星期,例如,从周二的变化freqdate_range

df.index = pd.to_datetime(df.index, format='%d/%m/%Y')

dtr = pd.date_range('01.01.2020', '31.03.2020', freq='W-Tue')
empty = pd.DataFrame(index=dtr)

df = pd.merge_asof(empty, 
                   df, 
                   left_index=True, 
                   right_index=True, 
                   tolerance=pd.Timedelta(7, 'd')).fillna(0)
print (df)
            value  expectation
2020-01-07    0.0          0.0
2020-01-14    0.0          0.0
2020-01-21    0.0          0.0
2020-01-28    0.0          0.0
2020-02-04   34.0         40.0
2020-02-11    0.0          0.0
2020-02-18    0.0          0.0
2020-02-25    0.0          0.0
2020-03-03   35.0         38.0
2020-03-10    0.0          0.0
2020-03-17    0.0          0.0
2020-03-24    0.0          0.0
2020-03-31   40.0         44.0

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章