How to maintain order of data frame when making pandas pivot table

273 Views Asked by At

trying to make a heat map out of a pivot table but am having trouble keeping the order of how I sorted my original data frame. Below is a sample code of what my data looks exactly like and how I made my pivot table.

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')

Since I sorted on "Skill 1 Type", I would like to have the pivot table's y-axis labels keep the same order of how "Skill 1" appears in my sorted dataframe. So ideally, I would have (Data Governance, Python, Communication) rather than (Communication, Data Governance, Python) on my y axis. What are some ways I can do this? Thank you!

1

There are 1 best solutions below

2
On

You can save the original order and then use reindex to swap the columns and rows.

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