如何将 DateTime multiindex 改回正常的 DateTimeindex?

How to chance DateTime multiindex back into normal DateTime index?

我有两个数据帧,它们的索引不同,如下所示;

df1:

                 C1
   Y     M  D
    2020  5  1   5
             2   7
             3   34
             4   4
             5   98

df2

                C1 
    Date
    2020-5-6   2
    2020-5-7   11
    2020-5-8   15
    2020-5-9   3
    2020-5-10  8

由于清理和分组的方式等原因,索引采用不同的格式。 我需要将这些数据框合并在一起。

有没有简单地将多索引转换回单个索引的方法? 或者我可以按原样合并它们吗?我似乎无法弄清楚。

非常感谢任何帮助!

这是另一种比链接问题更清晰的方法:

df.index = pd.to_datetime([f'{y}-{m}-{d}' for y,m,d in df.index],
                          format='%Y-%m')

输出:

            C1
2020-05-01   5
2020-05-02   7
2020-05-03  34
2020-05-04   4
2020-05-05  98

注意:对于Python 2.7,而不是f'{y}-{m}-{d}',做

'{}-{}-{}'.format(y,m,d)

我们有函数 to_datetime,名称正确

df.index=pd.to_datetime(df.rename_axis(['year','month','day']).index.to_frame())
df
Out[435]: 
            C1
2020-05-01   5
2020-05-02   7
2020-05-03  34
2020-05-04   4
2020-05-05  98