Search code examples
pythonpandasplotly

How can I make a heatmap from a repetitive dataframe?


I've got a df that has three columns, one of them has a repetitive pattern, the df looks like this

>>> df
        date        hour        value      
   0  01/01/2022     1        0.267648 
   1  01/01/2022     2        1.564420  
   2  01/01/2022    ...       0.702019 
   3  01/01/2022     24       1.504663  
   4  01/02/2022     1        0.309097 
   5  01/02/2022     2        0.309097 
   6  01/02/2022    ...       0.309097 
   7  01/02/2022     24       0.309097 
>>> 

I want to make a heatmap with this, the x-axis would be the month, the y axis the hour of the day and the value would be the median of all the values in that specific hour from everyday in the month.


Solution

  • import seaborn as sns
    import matplotlib.pyplot as plt
    
    df.date = pd.to_datetime(df.date)
    df['month'] = df.date.dt.month
    
    pivot = df.pivot_table(columns='month', index='hour', values='value', aggfunc='median')
    
    sns.heatmap(pivot.sort_index(ascending=False))
    plt.show()
    

    Output:

    enter image description here