1

I have the following dataframe

The index is days of the weeks and the columns are numbers from 0 to 23 (hours of the day) The cell values are counts

    0  1  2 ....
Mon 2  2  4
Tue 5  6  2
Wed 3  1  1
.
.
.

The dataframe is a result of

df.crosstab(df['DoW'],df['Hour'])

I tried using

hourdow.reindex(["Mon", "Tue", "Wed","Thu","Fri","Sat",'Sun'])

To get the Dataframe sorted but when i plot the graph is still end up with the index being sorted alphabetically on the heatmap. Is there anyway to reorder the rows?

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
Mobix
  • 103
  • 10
  • See [jezrael](https://stackoverflow.com/questions/47741400/pandas-dataframe-group-and-sort-by-weekday?rq=1) – run-out May 09 '20 at 21:44

1 Answers1

3

You can set df['DoW'] as a category first:

import seaborn as sns
import pandas as pd

days_order = ["Mon", "Tue", "Wed","Thu","Fri","Sat",'Sun']
df = pd.DataFrame({'Dow':np.random.choice(days_order,100),
                  'Hr':np.random.randint(0,4,100)})
df['Dow'] = pd.Categorical(df['Dow'], 
                           categories=days_order,
                           ordered=True)

sns.heatmap(pd.crosstab(df['Dow'],df['Hr']))

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72