[Python] What is energy data? Calender Heatmap [Plotly] Memo

Overview

Implementation

gen_calmap


def gen_calmap(df,column_name_lst,aggr='sum',height= 260,width = 900):
    try:
        for column_name in column_name_lst:

            # heatmap_df_lst generation
            heatmap_df_lst = _calender_heatmap_df(df,column_name,aggr)
            
            for heatmap_df in heatmap_df_lst:
                fig = px.imshow(heatmap_df[0],
                                x=heatmap_df[0].columns.unique(),
                                y=heatmap_df[0].index.unique(),
                                labels={'y':'Weekday','x':'Week','color':column_name},
                                width=width,
                                height=height,
                                aspect='auto',
                                )
                
                #Insert a gap between cells
                fig.data[0]['ygap']=1
                fig.data[0]['xgap']=1
                
                fig.update_traces(
                    text = heatmap_df[1],
                    hovertemplate="Date: %{text} <br>Week: %{x} <br>Weekday: %{y} <br> "+ column_name +": %{z}"
                )
                fig.show()
    except:
        print('Failed to generate calmap.')

def _calender_heatmap_df(df,column_name,aggr='sum'):
    heatmap_df_lst =[]
    
    #DataFrame regeneration
    data = pd.DataFrame(eval("df[column_name].resample('D').{}()".format(aggr)))
    data.index = pd.to_datetime(data.index)
    
    ## add data
    data['week'] = pd.to_datetime(data.index).strftime('Week:%W')
    data['weekday'] = pd.to_datetime(data.index).weekday
    data['date'] = pd.to_datetime(data.index).strftime('%Y/%m/%d')

    weekday_dic = {0:'Mon',1:'Tue',2:'Wed',3:'Thr',4:'Fri',5:'Sat',6:'Sun'}
    
    #Data expansion
    for year in data.index.year.unique():
        #heatmap generation
        heatmap_df = data.loc[data.index.year == year,:].pivot_table(index='weekday',columns='week',values=column_name)
        
        #Sort the days of the week in the order of Monday → Sunday
        heatmap_df = heatmap_df.rename(index=weekday_dic)
        
        #Generate date df
        date_df = data.loc[data.index.year == year,:].pivot(index='weekday',columns='week',values='date')
        date_df = date_df.rename(index=weekday_dic)
        
        #Add df to list
        heatmap_df_lst.append([heatmap_df,np.array(date_df)])
        
    return heatmap_df_lst

Run


gen_calmap(df=data,column_name_lst=['Electric energy[kWh]','Gas amount[m3]'],aggr='sum')

result

plotly_calmap.gif

Summary

Recommended Posts

[Python] What is energy data? Calender Heatmap [Plotly] Memo
What is python
What is Python
[Python] What is Pipeline ...
[Python] What is virtualenv
[Python] Python and security-① What is Python?
Python data type summary memo
[Python] * args ** What is kwrgs?
What is a python map?
Python Basic Course (1 What is Python)
What is Python? What is it used for?
[Python] What is a zip function?
[Python] What is a with statement?
[Python] What is @? (About the decorator)
[python] What is the sorted key?
Python for statement ~ What is iterable ~
What is the python underscore (_) for?
Python> What is an extended slice?
[Python] What is pandas Series and DataFrame?
[Python] What is inherited by multiple inheritance?
What is NaN? NaN Zoya (Python) (394 days late)
What kind of programming language is Python?
Python learning basics ~ What is type conversion? ~
Python memo using perl --format is convenient.
What is "mahjong" in the Python library? ??
Python data structure and operation (Python learning memo ③)
What is a dog? Python installation volume
[Python] Complete preprocessing Memo as it is
Python memo
python memo
Python memo
python memo
Python memo
Python memo
Python memo
[What is an algorithm? Introduction to Search Algorithm] ~ Python ~
What is "functional programming" and "object-oriented" in Python?
What is wheezy in the Docker Python image?
I tried Python! ] I graduated today from "What is Python! Python!"!
[Python] Conversion memo between time data and numerical data
What are you comparing with Python is and ==?
[Introduction to Udemy Python 3 + Application] 54. What is Docstrings?
Tell me what a conformal map is, Python!