Creating a HeatMap from a Pandas MultiIndex Series

I have a Pandas DF and I need to create a Heatmap. My data looks like this and I'd like to put the Years in Columns, the Days in rows and then use that with Seaborn to create a heatmap

I tried multiple ways but I was always getting "inconsistent shape" when I chose the DF, so any recommendation on how to transform it?

Year and Days are the index of this series

2016

  Tuesday  4
  Wednesady 6
  .....

2017

  Tuesday  4.4
  Monday   3.5
 ....

import seaborn as sns ax = sns.heatmap(dayofweek)

Upvotes: 0

Views: 8091

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40697

If you have a DataFrame like this:

years = range(2016,2019)
months = range(1,6)

df = pd.DataFrame(index=pd.MultiIndex.from_product([years,months]))
df['vals'] = np.random.random(size=len(df))

You can reformat the data to a rectangular shape using:

df2 = df.reset_index().pivot(columns='level_0',index='level_1',values='vals')

sns.heatmap(df2)

enter image description here

Upvotes: 10

Related Questions