codetech
codetech

Reputation: 113

Fill missing year and week values dynamically based on series in Python pandas

have a csv with 2 columns. The file contains some missing year-week values based on the series.

Input:-

Date       A   
2019-51   10 
2020-04   20

Output:-

Date      A   
2019-51  10 
2019-52  10
2020-01  10
2020-02  10
2020-03  10
2020-04  20

I need pandas python code to generate the above output

Upvotes: 0

Views: 287

Answers (1)

BENY
BENY

Reputation: 323226

IIUC we use resample

df.index=pd.to_datetime(df.Date+'0',format = '%Y-%W%w')
df=df.resample('W').ffill()
df.index=df.index.strftime('%Y-%W')
df=df.drop('Date',1).reset_index()
df
Out[57]: 
     index   A
0  2019-51  10
1  2020-00  10# this not ISO week
2  2020-01  10
3  2020-02  10
4  2020-03  10
5  2020-04  20

If you would like from 01

df.index=pd.to_datetime(df.Date+'0',format = '%G-%V%w')
df=df.resample('W').ffill()
df.index=df.index.strftime('%Y-%V')
df=df.drop('Date',1).reset_index()
df
Out[62]: 
     index   A
0  2019-51  10
1  2019-52  10
2  2020-01  10
3  2020-02  10
4  2020-03  10
5  2020-04  20

Upvotes: 3

Related Questions