Python 将多索引转换为单个日期
我有一个数据框架,其中索引是一个多索引,如下所示Python 将多索引转换为单个日期,python,pandas,datetime,indexing,multi-index,Python,Pandas,Datetime,Indexing,Multi Index,我有一个数据框架,其中索引是一个多索引,如下所示 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 由于我需要每日值,我希望将其转换为如下列 1 2 3 4 5 2020 6 7
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
由于我需要每日值,我希望将其转换为如下列
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()
非常感谢任何帮助 如果索引中的级别仅为
年
和月
级别,则使用列表理解和连接字符串的更改格式:
#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, b, c) for a, b, c in df.index])
然后:
df1 = df.resample('D').ffill()
我似乎在01'anyideas?@spcol中遇到语法错误-您的python版本是什么?如果将
01
更改为1
会起作用吗?恐怕也不起作用。使用2.7.16版。@spcol-in索引也为天?不仅仅是年和月?仅仅是月和年,我不应该在上面使用d。你的编辑工作完美!谢谢