如何按周和年绘制时间序列数据?

Jam*_*ams 3 python matplotlib

我有一个简单的时间序列数据框('cats')。按年和周进行的交易。我只想要一个以年和周为轴的折线图。

    year    week    transactions
0   2013    25      1824
1   2013    26      1876392
2   2013    27      2048913
3   2013    28      2060043
4   2013    29      1864779
5   2013    30      1844886
6   2013    31      2089084
7   2013    32      2017478
8   2013    33      1927819
9   2013    34      1965046
Run Code Online (Sandbox Code Playgroud)

我可以让这条线在这里工作,但它只绘制与索引的关系

plt.plot(cats['total_sales'])

在此处输入图片说明

但是当我尝试添加一个轴时会发生这样的事情

plt.plot(cats['year'],cats['total_sales'])

在此处输入图片说明

aso*_*uin 5

您可以根据年份和周数创建一列正确的日期时间:

# %U assumes Monday as first day of the week. Use %W for Sunday
cats['week_yr'] = pd.to_datetime(cats['year'].astype(str) + ' ' + cats['week'].astype(str) + ' 1',
                                format='%Y %U %w')
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

cats.plot.line(x='week_yr', y='transactions')
Run Code Online (Sandbox Code Playgroud)

并得到:

在此处输入图片说明