根据Python中的系列动态填充缺少的年和周值

2024-09-26 22:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个包含两列的csv。该文件包含一些基于系列的缺少的年-周值

输入:-

Date       A   
2019-51   10 
2020-04   20

输出:-

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

我需要python代码来生成上述输出


Tags: 文件csv代码date周值
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:48

IIUC我们使用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

如果你想从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

相关问题 更多 >

    热门问题