繁体   English   中英

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

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

有一个带有 2 列的 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

我需要pandas python代码来生成上面的输出

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM