Python - 绘制周分布

Python - plotting week-wise distribution

我有一个数据框,看起来像:

       date
1      2008-10-05
10     2007-03-30
100    2008-07-05
1000   2007-03-30
1001   2014-08-14
1002   2007-09-30
1003   2007-06-14
1004   2006-01-13
1005   2006-08-04
1006   2007-06-14
1007   2008-11-30

我想要做的是绘制一个直方图,显示按比例缩小到一周的日期分布。 例如, 索引是一个图片 ID,我想深入了解 2006 年 10 月的第一周拍摄了多少张照片。换句话说,我想要一个每周直方图。

df['week'].iplot(kind='histogram') 仅返回周数,但我想将其与年份联系起来。

如果有人可以帮助我使用 plot.ly 绘制直方图,那就太好了。 matplotlib 图也可以。

感谢您的帮助。

编辑:以下是我的问题的最终解决方案:

df_new = df.groupby(['year','week']).count()['date']
df_dict = df_new.to_dict()
df_tups = [(' wk#'.join(map(str,key)), df_dict[key]) for key in df_dict.keys()]
df_tups = sorted(df_tups, key=lambda x : (x[0], x[1]))
x = ["'"+tup[0][2:] for tup in df_tups]
y = [tup[1] for tup in df_tups]
trace1 = go.Bar(
            x = x,
            y = y
        )

data = [trace1]
layout = go.Layout(
    xaxis=dict(tickangle=45)
)
fig = dict(data=data, layout=layout)
py.iplot(fig)

让你的 df 为:

df =    date
7   2012-06-11
3   2012-09-28
19  2012-10-01
2   2012-10-03
6   2012-12-22
1   2013-02-19
9   2013-02-28
12  2013-03-12
4   2013-04-04
17  2013-04-18
11  2013-05-17
5   2013-07-07
14  2013-10-22
13  2014-01-16
15  2014-02-25
18  2014-03-19
0   2014-03-31
16  2014-04-01
8   2014-04-27
10  2014-09-20

您想做的是:

df['week'] = df['date'].map(lambda x: x.isocalendar()[1])
df['year'] = df['date'].map(lambda x: x.isocalendar()[0])
data = df.groupby(['year','week']).count()

那会给你:

        date
year    week   count    
2012    24       1
        39       1
        40       2
        51       1
2013    8        1
        9        1
        11       1
        14       1
        16       1
        20       1
        27       1
        43       1
2014    3        1
        9        1
        12       1
        14       2
        17       1
        38       1

现在,如果你想做直方图,你可以做每年,也可以做整个周期。但是你必须为每一年增加 52 周,因为它高于你的集合中的第一年(年),否则它会混淆不同年份的周数

当数据帧/系列的一列为 datetime 类型时,您有一个特殊的访问器 dt 来应用矢量化日期时间函数(与 str 特殊的方法相同字符串系列的访问器)。使用此功能获得您期望的分组:

df.groupby([df.date.dt.year, df.date.dt.week]).size()
Out[16]: 
date  date
2006  2       1
      31      1
2007  13      2
      24      2
      39      1
2008  27      1
      40      1
      48      1
2014  33      1
dtype: int64