python - Pandas :按日历周分组,然后为实际日期时间绘制分组条形图

标签 python datetime pandas calendar group-by

编辑

我找到了一个非常好的解决方案并将其发布在下面作为答案。 结果将如下所示:

enter image description here


您可以为此问题生成的一些示例数据:

codes = list('ABCDEFGH'); 
dates = pd.Series(pd.date_range('2013-11-01', '2014-01-31')); 
dates = dates.append(dates)
dates.sort()
df = pd.DataFrame({'amount': np.random.randint(1, 10, dates.size), 'col1': np.random.choice(codes, dates.size), 'col2': np.random.choice(codes, dates.size), 'date': dates})

导致:

In [55]: df
Out[55]:
    amount col1 col2       date
0        1    D    E 2013-11-01
0        5    E    B 2013-11-01
1        5    G    A 2013-11-02
1        7    D    H 2013-11-02
2        5    E    G 2013-11-03
2        4    H    G 2013-11-03
3        7    A    F 2013-11-04
3        3    A    A 2013-11-04
4        1    E    G 2013-11-05
4        7    D    C 2013-11-05
5        5    C    A 2013-11-06
5        7    H    F 2013-11-06
6        1    G    B 2013-11-07
6        8    D    A 2013-11-07
7        1    B    H 2013-11-08
7        8    F    H 2013-11-08
8        3    A    E 2013-11-09
8        1    H    D 2013-11-09
9        3    B    D 2013-11-10
9        1    H    G 2013-11-10
10       6    E    E 2013-11-11
10       6    F    E 2013-11-11
11       2    G    B 2013-11-12
11       5    H    H 2013-11-12
12       5    F    G 2013-11-13
12       5    G    B 2013-11-13
13       8    H    B 2013-11-14
13       6    G    F 2013-11-14
14       9    F    C 2013-11-15
14       4    H    A 2013-11-15
..     ...  ...  ...        ...
77       9    A    B 2014-01-17
77       7    E    B 2014-01-17
78       4    F    E 2014-01-18
78       6    B    E 2014-01-18
79       6    A    H 2014-01-19
79       3    G    D 2014-01-19
80       7    E    E 2014-01-20
80       6    G    C 2014-01-20
81       9    H    G 2014-01-21
81       9    C    B 2014-01-21
82       2    D    D 2014-01-22
82       7    D    A 2014-01-22
83       6    G    B 2014-01-23
83       1    A    G 2014-01-23
84       9    B    D 2014-01-24
84       7    G    D 2014-01-24
85       7    A    F 2014-01-25
85       9    B    H 2014-01-25
86       9    C    D 2014-01-26
86       5    E    B 2014-01-26
87       3    C    H 2014-01-27
87       7    F    D 2014-01-27
88       3    D    G 2014-01-28
88       4    A    D 2014-01-28
89       2    F    A 2014-01-29
89       8    D    A 2014-01-29
90       1    A    G 2014-01-30
90       6    C    A 2014-01-30
91       6    H    C 2014-01-31
91       2    G    F 2014-01-31

[184 rows x 4 columns]

我想按日历周和 col1 的值进行分组。像这样:

kw = lambda x: x.isocalendar()[1]
grouped = df.groupby([df['date'].map(kw), 'col1'], sort=False).agg({'amount': 'sum'})

导致:

In [58]: grouped
Out[58]:
           amount
date col1
44   D          8
     E         10
     G          5
     H          4
45   D         15
     E          1
     G          1
     H          9
     A         13
     C          5
     B          4
     F          8
46   E          7
     G         13
     H         17
     B          9
     F         23
47   G         14
     H          4
     A         40
     C          7
     B         16
     F         13
48   D          7
     E         16
     G          9
     H          2
     A          7
     C          7
     B          2
...           ...
1    H         14
     A         14
     B         15
     F         19
2    D         13
     H         13
     A         13
     B         10
     F         32
3    D          8
     E         18
     G          3
     H          6
     A         30
     C          9
     B          6
     F          5
4    D          9
     E         12
     G         19
     H          9
     A          8
     C         18
     B         18
5    D         11
     G          2
     H          6
     A          5
     C          9
     F          9

[87 rows x 1 columns]

然后我想要这样生成一个图: enter image description here 这意味着:x 轴上的日历周和年份(日期时间)以及每个分组的 col1 一个条。

我面临的问题是:我只有描述日历周的整数(图中的 KW),但我必须以某种方式合并回它上面的日期以获得按年份标记的刻度。此外,我不能只绘制分组的日历周,因为我需要正确的项目顺序(kw 47、kw 48(2013 年)必须位于 kw 1 的左侧(因为这是 2014 年))。


编辑

我从这里想通了: http://pandas.pydata.org/pandas-docs/stable/visualization.html#visualization-barplot分组的条形图需要是列而不是行。所以我想了想如何转换数据,找到了方法pivot,结果证明这是一个很棒的函数。 reset_index 需要将多索引转换为列。最后,我用零填充 NaN:

A = grouped.reset_index().pivot(index='date', columns='col1', values='amount').fillna(0)

将数据转换成:

col1   A   B   C   D   E   F   G   H
date
1      4  31   0   0   0  18  13   8
2      0  12  13  22   1  17   0   8
3      3  10   4  13  12   8   7   6
4     17   0  10   7   0  25   7   4
5      7   0   7   9   8   6   0   7
44     0   0   2  11   7   0   0   2
45     9   3   2  14   0  16  21   2
46     0  14   7   2  17  13  11   8
47     5  13   0  15  19   7   5  10
48    15   8  12   2  20   4   7   6
49    20   0   0  18  22  17  11   0
50     7  11   8   6   5   6  13  10
51     8  26   0   0   5   5  16   9
52     8  13   7   5   4  10   0  11

这看起来像文档中要绘制成分组条形图的示例数据:

A. plot(kind='bar')

得到这个:

enter image description here

而我对轴有问题,因为它现在已排序(从 1-52),这实际上是错误的,因为在这种情况下日历周 52 属于 2013 年......关于如何合并回的任何想法日历周的真实日期时间并将它们用作 x 轴刻度?

最佳答案

我认为resample('W')是执行此操作的更好方法 - 默认情况下,它按星期日结束的周分组('W' 与 'W-SUN' 相同)但您可以指定任何您想要的。

在你的例子中,试试这个:

grouped = (df
    .groupby('col1')                
    .apply(lambda g:               # work on groups of col1
        g.set_index('date')        
        [['amount']]
        .resample('W').agg('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')

它应该打印您的数据表并绘制与您的类似的图,但带有“真实”日期标签:

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

关于python - Pandas :按日历周分组,然后为实际日期时间绘制分组条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24203106/

相关文章:

python - 统计模型多元方差分析 : IndexError: index 1 is out of bounds for axis 0 with size 1

python - 在 Python 中将二维 RGB 数组中的 'R' 和 'B' 元素设为零

java - 使用 Joda 时间库从 UTC 到 IST 的转换在 JAVA 中返回相同的值

python - 保留LDA pca的csv特征标签

python - 如何在 Pandas 中调试 Cython 代码?

python - 计算 Pandas 的亏损

python - 如何使用 mod_wsgi/django/python 生成线程安全的 pdf

python - Django REST Framework : Disable migration of all built in schemas, 即(auth.contenttypes.admin.等)

R函数返回时间序列ts()对象的开始和结束日期?

python-2.7 - 将俄语字符串转换为日期时间