尝试从数据透视表中制作热图,但无法保持原始数据框的排序顺序。下面是一个示例代码,展示了我的数据的外观以及我如何制作数据透视表。
simple_df = pd.DataFrame({'Skill 1': ['Python','Python','Python','Communication','Communication','Communication','Data Governance','Data Governance','Data Governance'], 'Skill 2': ['Python','Communication','Data Governance','Python','Communication','Data Governance','Python','Communication','Data Governance'],'Score':[1,0.9,0.4,0.9,1,0.4,0.4,0.4,1],'Skill 1 Type':['Programming','Programming','Programming','Written','Written','Written','Cyber','Cyber','Cyber']})
simple_df=simple_df.sort_values(by = ['Skill 1 Type'], ascending = [True], na_position = 'first')
test=simple_df.groupby(['Skill 1','Skill 2'], sort=True)['Score'].sum().unstack('Skill 2')
由于我对“技能 1 类型”进行排序,因此我希望数据透视表的 y 轴标签与“技能 1”在排序数据框中的显示顺序保持相同。因此,理想情况下,我的 y 轴上应该有(数据治理、Python、通信)而不是(通信、数据治理、Python)。我可以通过哪些方法来做到这一点?谢谢!
最佳答案
您可以保存原始顺序,然后使用重新索引来交换列和行。
original_order = simple_df["Skill 1"].unique()
(simple_df.pivot(index="Skill 1", columns="Skill 2", values="Score")
.reindex(index=original_order, columns=original_order))
Skill 2 Data Governance Python Communication
Skill 1
Data Governance 1.0 0.4 0.4
Python 0.4 1.0 0.9
Communication 0.4 0.9 1.0
关于python - 制作pandas数据透视表时如何保持数据框的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74214041/