This is how to get an index, of a Pivot-table, with names of months in the right order.
The problem came up in a course1 when making a Pivot table over passengers per year per month. Month should be in the index, but was ordered alphabetically instead of Jan, Feb, etc.
So here is a solution:
flights = sns.load_dataset("data/flights") # First convert months, as strings, to datetime objects flights["month"] = pd.to_datetime(flights["month"], format='%B') # Make a Pivot table. Now the index is in right order, but are ugly numbers fpt = flights.pivot_table(index="month", columns="year", values="passengers") # Now make the datetime objects to readable names of the months fpt.index = fpt.index.strftime('%B') sns.heatmap(fpt, cmap='magma') plt.show()
1. Python for Data Science and Machine Learning Bootcamp with Jose Portilla on Udemy.
Comments are closed.