I have a Pandas dataframe that looks like this:
JavaScript
x
7
1
store_id days times rating
2
100 monday '1:00pm - 3:00pm' 0
3
100 monday '3:00pm - 6:00pm' 1
4
100 monday '6:00pm - 9:00pm' 2
5
6
store n
7
Where there are ~60 stores and the ratings range from 0 – 2. I would like to create a 6×5 grid Seaborn of heatmaps, with one heatmap per store. I would like for the x-axis to be the days
and for the y-axis to be the times
.
I tried this:
JavaScript
1
6
1
f, axes = plt.subplots(5,6)
2
i=0
3
for store in df['store_id']:
4
sns.heatmap(data=df[df['store_id']==store]['rating'], ax=axes[i])
5
i+=1
6
This creates the 5×6 grid, but generates an error (‘Inconsistent shape between the condition and the input…’). What’s the best way to do this?
Advertisement
Answer
For heat map, you need to transpose/pivot your data so as the days
becomes columns (x-axis) and times
becomes index:
JavaScript
1
10
10
1
f, axes = plt.subplots(5,6)
2
3
# flatten axes for looping
4
axes = axes.ravel()
5
6
# use groupby to extract data faster
7
for ax, (store, data) in zip(axes, df.groupby('store_id')):
8
pivot = data.pivot_table(index='times', columns='days', values='rating')
9
sns.heatmap(data=pivot, ax=ax)
10