如何在Pandas中创建groupby子块?

2024-06-16 11:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含犯罪时间序列数据的数据帧,其中有一个关于犯罪的方面(如下所示)。我想在数据帧上执行一个分组图,这样就可以探索犯罪随时间的变化趋势。

    Offence                     Rolling year total number of offences       Month
0   Criminal damage and arson   1001                                        2003-03-31
1   Drug offences               66                                         2003-03-31
2   All other theft offences    617                                   2003-03-31
3   Bicycle theft               92                                    2003-03-31
4   Domestic burglary           282                                   2003-03-31

我有一些代码可以完成这项工作,但它有点笨拙,而且它失去了Pandas在一个单独的图上提供的时间序列格式。(我附上了一张图片来说明)。有人能给我推荐一个这样的情节的成语吗?

我会求助于Seaborn,但我不知道如何将xlabel格式化为timeseries。

[![subs = \[\]
for idx, (i, g) in enumerate(df.groupby("Offence")):
        subs.append({"data": g.set_index("Month").resample("QS-APR", how="sum" ).ix\["2010":\],
                     "title":i})

ax = plt.figure(figsize=(25,15))
for i,g in enumerate(subs):
    plt.subplot(5, 5, i)
    plt.plot(g\['data'\])
    plt.title(g\['title'\])
    plt.xlabel("Time")
    plt.ylabel("No. of crimes")
    plt.tight_layout()][1]][1]

Tags: of数据infortitle时间plt序列