将 pandas 数据帧的特定行转换为多索引

convert specific rows of pandas dataframe into multiindex

这是我的 DataFrame:

          0     1        2
0 0      0.0  20.0      NaN
  1      1.0  21.0      NaN
  2      2.0  22.0      NaN
  ID     NaN   NaN  11111.0
  Year   NaN   NaN   2011.0
1 0      3.0  23.0      NaN
  1      4.0  24.0      NaN
  2      5.0  25.0      NaN
  3      6.0  26.0      NaN
  ID     NaN   NaN  11111.0
  Year   NaN   NaN   2012.0

我想将 'ID' 和 'Year' 行转换为数据帧索引,其中 'ID' 为 level=0,'Year' 为 level=1。我尝试使用 stack() 但仍然无法理解。

已编辑:我想要的输出应如下所示:

                      0     1 
  11111  2011 0      0.0  20.0
              1      1.0  21.0
              2      2.0  22.0
         2012 0      3.0  23.0
              1      4.0  24.0
              2      5.0  25.0
              3      6.0  26.0 

这应该有效:

df1 = df.loc[pd.IndexSlice[:, ['ID', 'Year']], '2']
dfs = df1.unstack()
dfi = df1.index
dfn = df.drop(dfi).drop('2', axis=1).unstack()

dfn.set_index([dfs.ID, dfs.Year]).stack()