Home > OS >  Pandas Timeseries Plotting from Multi Index Dataframe
Pandas Timeseries Plotting from Multi Index Dataframe

Time:05-31

I have a multi index data frame which looks like:

                                          col1        col2        col3
timestamp        type        class
1653385980729    audio       dc           3           10          1
                             ec           5           7           2
                 video       dc           10          18          5
                             ec           7           14          4
1653385981729    audio       dc           4           8           4
                             ec           5           8           2
                 video       dc           9           15          3
                             ec           9           17          6
1653385982729    audio       dc           3           10          3
                             ec           6           8           2
                 video       dc           11          16          6
                             ec           9           18          6
.
.
.

Now I am trying to create some graphs out of columns of this dataframe. Each graph for different columns will look like this (don't mind the random values):

example graph

When I try to draw it by seperating columns and using plot() it becomes an absolute mess. How should I manipulate the dataframe to achieve what I want?

CodePudding user response:

Use Series.unstack by second and third level with flatten MultiIndex in columns:

df1 = df['col1'].unstack([1,2])
df1.columns = [f'{a}/{b}' for a, b in df1.columns]
print (df1)
               audio/dc  audio/ec  video/dc  video/ec
timestamp                                            
1653385980729         3         5        10         7
1653385981729         4         5         9         9
1653385982729         3         6        11         9

df1.plot()
  • Related