如何将DateTime多索引恢复为正常的DateTime索引?

问题描述 投票:0回答:2

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

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

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

无论如何,是否只是将多索引转换回单个索引?还是可以按原样合并它们?我似乎无法弄清楚。

任何帮助,不胜感激!

Dataframe 1

Dataframe 2

python pandas datetime pandas-groupby multi-index
2个回答
1
投票

这是比链接的问题还干净的另一种方法:

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

Note:对于Python 2.7,而不是f'{y}-{m}-{d}',请执行

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

0
投票

我们具有名称正确的功能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
© www.soinside.com 2019 - 2024. All rights reserved.