簡體   English   中英

使用日期范圍將月底數據轉換為 Pandas 上的每周數據

[英]using date range to convert month end data to weekly data on Pandas

我有一個 dataframe,如下所示。 是月末數據。

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

基本上,我正在嘗試將月末數據轉換為每周數據。 但是,不同的是,確切的月末日期可能與周日期范圍不匹配,因此它將落入周末日期(例如,31/01/2020 為 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)

該代碼有效,但我沒有得到確切的預期 output。感謝任何幫助。

使用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

如果還需要更改周的開始時間,例如從星期二開始更改freq中的date_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

下面給出的一段代碼會給你想要的結果:

for end_date in df["date"]:
    days_diff = (end_date  - pd.date_range(end=end_date , freq='W', periods=5)[-1])
    pd.date_range(end='2020-03-31', freq='W', periods=5) + days_diff

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM