1 回答
TA贡献1936条经验 获得超6个赞
矛盾的是,您想要的是第二个unstack调用:
In [14]: df
Out[14]:
sepal_length sepal_width petal_length petal_width
petal_length 0.935877 0.289742 1.000000 0.981379
petal_width 0.908977 0.321728 0.981379 1.000000
sepal_length 1.000000 0.445315 0.935877 0.908977
sepal_width 0.445315 1.000000 0.289742 0.321728
In [13]: df_sqr.unstack().unstack()
Out[13]:
petal_length petal_width sepal_length sepal_width
sepal_length 0.935877 0.908977 1.000000 0.445315
sepal_width 0.289742 0.321728 0.445315 1.000000
petal_length 1.000000 0.981379 0.935877 0.289742
petal_width 0.981379 1.000000 0.908977 0.321728
该文件提到,拆散了一系列的情况下等于支点,就像你在你的问题之嫌。
奖金
只是因为我很好奇,当我们为列和索引标签加上前缀时,堆栈和非堆栈之间的区别变得更加明显:
In [17]: df.columns = [f'columns_{i}' for i in df.columns]
In [18]: df.index = [f'index_{i}' for i in df.index]
.stack() 将行索引作为多索引的最左侧:
In [20]: df.stack()
Out[20]:
index_petal_length columns_sepal_length 0.935877
columns_sepal_width 0.289742
columns_petal_length 1.000000
columns_petal_width 0.981379
index_petal_width columns_sepal_length 0.908977
columns_sepal_width 0.321728
columns_petal_length 0.981379
columns_petal_width 1.000000
index_sepal_length columns_sepal_length 1.000000
columns_sepal_width 0.445315
columns_petal_length 0.935877
columns_petal_width 0.908977
index_sepal_width columns_sepal_length 0.445315
columns_sepal_width 1.000000
columns_petal_length 0.289742
columns_petal_width 0.321728
dtype: float64
.unstack() 将列索引作为多索引的最左侧:
In [21]: df.unstack()
Out[21]:
columns_sepal_length index_petal_length 0.935877
index_petal_width 0.908977
index_sepal_length 1.000000
index_sepal_width 0.445315
columns_sepal_width index_petal_length 0.289742
index_petal_width 0.321728
index_sepal_length 0.445315
index_sepal_width 1.000000
columns_petal_length index_petal_length 1.000000
index_petal_width 0.981379
index_sepal_length 0.935877
index_sepal_width 0.289742
columns_petal_width index_petal_length 0.981379
index_petal_width 1.000000
index_sepal_length 0.908977
index_sepal_width 0.321728
dtype: float64
添加回答
举报