如何根据 pandas.Multindex 添加行?

How do i add rows according to pandas.Multindex?

我正在使用如下所示的数据框

            0     1     2     3     4 
one   y   8.0   0.0   9.0  11.0   5.0 
      z  12.0  18.0   7.0   1.0  18.0 
two   x  14.0  15.0   9.0   9.0  18.0 
      y  10.0   7.0  13.0  14.0   1.0 
      z  19.0  16.0  13.0  13.0   6.0 
three x  15.0  15.0   5.0  14.0  18.0 
      y   3.0  15.0   7.0   5.0   1.0 

我想向 'one' 和 'three' 添加行,允许每个一级索引具有相同数量的二级行,如下所示:

            0     1     2     3     4 
one   x   NaN   NaN   NaN   NaN   NaN 
      y   8.0   0.0   9.0  11.0   5.0 
      z  12.0  18.0   7.0   1.0  18.0 
two   x  14.0  15.0   9.0   9.0  18.0 
      y  10.0   7.0  13.0  14.0   1.0 
      z  19.0  16.0  13.0  13.0   6.0 
three x  15.0  15.0   5.0  14.0  18.0 
      y   3.0  15.0   7.0   5.0   1.0 
      z   NaN   NaN   NaN   NaN   NaN 

有什么有效的方法可以实现吗?

试试这个:

idx = pd.MultiIndex.from_product(df.index.levels)

df.reindex(idx)

输出:

            0     1     2     3     4
one   x   NaN   NaN   NaN   NaN   NaN
      y   8.0   0.0   9.0  11.0   5.0
      z  12.0  18.0   7.0   1.0  18.0
three x  15.0  15.0   5.0  14.0  18.0
      y   3.0  15.0   7.0   5.0   1.0
      z   NaN   NaN   NaN   NaN   NaN
two   x  14.0  15.0   9.0   9.0  18.0
      y  10.0   7.0  13.0  14.0   1.0
      z  19.0  16.0  13.0  13.0   6.0

让我们做 unstack + stack

df.unstack().stack(dropna=False)

            0     1     2     3     4
one   x   NaN   NaN   NaN   NaN   NaN
      y   8.0   0.0   9.0  11.0   5.0
      z  12.0  18.0   7.0   1.0  18.0
three x  15.0  15.0   5.0  14.0  18.0
      y   3.0  15.0   7.0   5.0   1.0
      z   NaN   NaN   NaN   NaN   NaN
two   x  14.0  15.0   9.0   9.0  18.0
      y  10.0   7.0  13.0  14.0   1.0
      z  19.0  16.0  13.0  13.0   6.0