猿问

pandas 将多索引 dafaframe 的索引重置为日期值并将其他索引转换为列

我有一个多索引数据框,如下所示:


                                                                   number

location                   category         created_on  

Arab Republic of Egypt      ACCESS          2018-06-25 00:00:00        4

                            ACCOUNT         2018-04-24 04:00:00        3

                                            2018-05-31 04:00:00        3

                                            2018-06-28 00:00:00        3

                        ACTIVE DIRECTORY    2018-04-01 00:00:00        3

... ... ... ...

United States of America    WINDOWS 10      2018-09-25 04:00:00        8

                                            2018-09-25 08:00:00       13

                                            2018-09-26 08:00:00       12

                                            2018-09-27 08:00:00        8

                                            2018-09-27 12:00:00        9

我想将其转换为以日期列为索引的数据框,但不丢失列号中的计数,新数据框应该是这样的:


created_on              number       category       location

2018-06-25 00:00:00          4       ACCESS         Arab Republic of Egypt

2018-04-24 04:00:00          3       ACCOUNT        Arab Republic of Egypt

2018-05-31 04:00:00          3       ACCOUNT        Arab Republic of Egypt

2018-06-28 00:00:00          3       ACCOUNT        Arab Republic of Egypt

2018-04-01 00:00:00          3  ACTIVE DIRECTORY    Arab Republic of Egypt     

... ... ... ...

2018-09-25 04:00:00          8     WINDOWS 10       United States of America

2018-09-25 08:00:00         13     WINDOWS 10       United States of America

2018-09-26 08:00:00         12     WINDOWS 10       United States of America

2018-09-27 08:00:00          8     WINDOWS 10       United States of America

2018-09-27 12:00:00          9     WINDOWS 10       United States of America

我怎样才能做到这一点?


月关宝盒
浏览 116回答 1
1回答

繁星点点滴滴

swaplevel在级别上使用0,2然后reset_index在级别1和上使用2:df1 = df.swaplevel(0, 2).reset_index(level=[1, 2])或者另一个想法先使用然后在列上reset_index使用:set_indexcreated_atdf1 = df.reset_index().set_index('created_on')结果:print(df1)                             category                  location  numbercreated_on                                                             2018-06-25 00:00:00            ACCESS    Arab Republic of Egypt       42018-04-24 04:00:00           ACCOUNT    Arab Republic of Egypt       32018-05-31 04:00:00           ACCOUNT    Arab Republic of Egypt       32018-06-28 00:00:00           ACCOUNT    Arab Republic of Egypt       32018-04-01 00:00:00  ACTIVE DIRECTORY    Arab Republic of Egypt       3...2018-09-25 04:00:00        WINDOWS 10  United States of America       82018-09-25 08:00:00        WINDOWS 10  United States of America      132018-09-26 08:00:00        WINDOWS 10  United States of America      122018-09-27 08:00:00        WINDOWS 10  United States of America       82018-09-27 12:00:00        WINDOWS 10  United States of America       9
随时随地看视频慕课网APP

相关分类

Python
我要回答