问题描述
1
2
3
4
5
2020 6
7
8
9
10
11
12
由于我需要每日值,因此希望将其转换为如下所示的列;
Date
2020/01/01
2020/02/01
2020/03/01
2020/04/01
2020/05/01
etc
以便我可以使用;
df.set_index('Date').resample('D').ffill()
任何帮助,不胜感激!
解决方法
如果索引中只有year
和month
级别,则对合并的字符串使用列表理解和更改格式:
#python 3
df.index = pd.to_datetime([f'{a}-{b}-01' for a,b in df.index])
#python 2
df.index = pd.to_datetime(['{}-{}-01'.format(a,b) for a,b in df.index])
如果还有几天:
#python 3
df.index = pd.to_datetime([f'{a}-{b}-{c}' for a,b,c in df.index])
#python 2
df.index = pd.to_datetime(['{}-{}-{}'.format(a,c) for a,c in df.index])
然后:
df1 = df.resample('D').ffill()