Pandas重置MultiIndex的内部级别

KOB*_*KOB 9 python pandas

我有以下格式的DF:

                   col1    col2
ID          Date
 1    1993-12-31      4       6
      1994-12-31      8       5
      1995-12-31      4       7
      1996-12-31      3       3
 2    2000-12-31      7       8
      2001-12-31      5       9
      2002-12-31      8       4
Run Code Online (Sandbox Code Playgroud)

我想重置'Date'索引,给出以下内容:

             col1    col2
ID    Date
 1       0      4       6
         1      8       5
         2      4       7
         3      3       3
 2       0      7       8
         1      5       9
         2      8       4
Run Code Online (Sandbox Code Playgroud)

我认为只是df.reset_index(level='Date', inplace=True, drop=True)会这样做,但事实并非如此.

use*_*203 5

使用set_indexcumcount:

tmp = df.reset_index('Date', drop=True)
tmp.set_index(df.groupby(level=0).cumcount().rename('Date'), append=True)

         col1  col2
ID Date
1  0        4     6
   1        8     5
   2        4     7
   3        3     3
2  0        7     8
   1        5     9
   2        8     4
Run Code Online (Sandbox Code Playgroud)


cs9*_*s95 5

使用pd.MultiIndex.from_arraysgroupby+ cumcount

df.index = pd.MultiIndex.from_arrays(
    [df.index.get_level_values(0), df.groupby(level=0).cumcount()],
    names=['ID', 'Date'])
Run Code Online (Sandbox Code Playgroud)

df
         col1  col2
ID Date            
1  0        4     6
   1        8     5
   2        4     7
   3        3     3
2  0        7     8
   1        5     9
   2        8     4
Run Code Online (Sandbox Code Playgroud)

这不会推广到N个级别,但是df.index.set_levels我应该忘记一个等效的...

  • 我发现此解决方案最容易遵循。 (2认同)