Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将多索引转换为单个日期_Python_Pandas_Datetime_Indexing_Multi Index - Fatal编程技术网

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。你的编辑工作完美!谢谢