重塑多索引数据框

Reshape a multi-index dataframe

arrays = [['indcator_1', 'indcator_1', 'indcator_2', 'indcator_2', 'indcator_3', 'indcator_3', 'indcator_4', 'indcator_4'], ['2018', '2019', '2018', '2019', '2018', '2019', '2018', '2019']]

tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['indicators', 'state'])
df = pd.DataFrame(np.random.randn(3, 8), index=['AZ', 'CA', 'IL'], columns=index)

df
Out[5]: 
indicators indcator_1           indcator_2           indcator_3            \
state            2018      2019       2018      2019       2018      2019   
AZ           0.823890  0.165838  -1.207324  0.991570   0.424288 -0.697368   
CA           0.323375 -1.301540   1.245174 -0.542040  -0.305037 -0.148536   
IL           0.283575  0.095836   0.542553 -0.179618   1.989065  0.914899   

indicators indcator_4            
state            2018      2019  
AZ          -1.544907 -0.286541  
CA           1.168241  1.702455  
IL           0.524246  2.031239  

我想重塑它:

有办法吗?我无法在任何地方找到针对此特定案例的解决方案。

对于问题的错误表述,我们深表歉意。我是新来的。

感谢您的帮助!

你试过了吗stack

df.stack()