Pandas: Group by calendar-week, then plot grouped barplots for the real datetime

前端 未结 3 1662
情书的邮戳
情书的邮戳 2021-01-30 15:05

EDIT

I found a quite nice solution and posted it below as an answer. The result will look like this:

\"ent

3条回答
  •  感情败类
    2021-01-30 15:34

    I think resample('W') is a better way to do this - by default it groups by weeks ending on Sunday ('W' is the same as 'W-SUN') but you can specify whatever you want.

    In your example, try this:

    grouped = (df
        .groupby('col1')                
        .apply(lambda g:               # work on groups of col1
            g.set_index('date')        
            [['amount']]
            .resample('W', how='sum')  # sum the amount field across weeks
        )
        .unstack(level=0)              # pivot the col1 index rows to columns
        .fillna(0)
    )
    grouped.columns=grouped.columns.droplevel()   # drop the 'col1' part of the multi-index column names
    print grouped
    grouped.plot(kind='bar')
    

    which should print your data table and make a plot similar to yours, but with "real" date labels:

    col1         A   B   C   D   E   F   G   H
    date                                      
    2013-11-03  18  0   9   0   8   0   0   4 
    2013-11-10  4   11  0   1   16  2   15  2 
    2013-11-17  10  14  19  8   13  6   9   8 
    2013-11-24  10  13  13  0   0   13  15  10
    2013-12-01  6   3   19  8   8   17  8   12
    2013-12-08  5   15  5   7   12  0   11  8 
    2013-12-15  8   6   11  11  0   16  6   14
    2013-12-22  16  3   13  8   8   11  15  0 
    2013-12-29  1   3   6   10  7   7   17  15
    2014-01-05  12  7   10  11  6   0   1   12
    2014-01-12  13  0   17  0   23  0   10  12
    2014-01-19  10  9   2   3   8   1   18  3 
    2014-01-26  24  9   8   1   19  10  0   3 
    2014-02-02  1   6   16  0   0   10  8   13
    

提交回复
热议问题