Search code examples
pythonpandasdataframedata-analysis

how to split a dataframe based on the unique channel name for graph plotting


I have been trying to split a dataframe based on a unique channel name and then plot a graph across different weeks for progress demonstration using Colab.

Here is my attempt:

import pandas as pd
  
#read and append all the worksheets into a single dataframe
all_data = []
for ws in wb.worksheets():
  rows=ws.get_all_values()
  df=pd.DataFrame.from_records(rows[1:],columns=rows[0])
  all_data.append(df)
    
data = pd.concat(all_data)
  
#Change data type
data['Week'] = pd.to_datetime(data['Week'], format='%d/%m/%Y')
data['Channel'] = data['Channel'].astype('str')
data['Times of alarms'] = data['Times of alarms'].astype('int')
    
#Create a new dataframe for analysis
subchannel_df = data[['Channel','Week','Times of alarms']].copy()
subchannel = subchannel_df.groupby(by=['Channel','Week']).agg({'Times of alarms' : 'sum'})
subchannel

enter image description here

How do I split them and plot all the bar charts based on unique Channel name accordingly?

What I hope to achieve for a channel: enter image description here

Thank you in advance


Solution

  • After changing the data type, you could make a pivot table with 'channel' as columns, 'Week' as the index.

    subchannel_df = data.pivot_table('Time of alarms', index = 'Week', column='Channel', aggfunc='sum')
    

    then if you would like to either put all channel together in one bar plot,

    ax= subchannel_df.plot.bar(rot=0)
    

    or focus on a certain channel, let's say 'test_chan'

    ax= subchannel_df.plot.bar(y='test_chan',rot=0)