Python 如何使用strftime以正确的顺序绘制月份名称?

Python 如何使用strftime以正确的顺序绘制月份名称?,python,pandas,matplotlib,Python,Pandas,Matplotlib,下面是我的数据帧的快速预览: local_date amount 0 2017-08-16 10.00 1 2017-10-26 21.70 2 2017-11-04 5.00 3 2017-11-12 37.20 4 2017-11-13 10.00 5 2017-11-18 31.00 6 2017-11-27 14.00 7 2017-11-29 10.00 8 2017-11-30 37.20 9 2017-12-16

下面是我的数据帧的快速预览:

   local_date  amount
0  2017-08-16   10.00
1  2017-10-26   21.70
2  2017-11-04    5.00
3  2017-11-12   37.20
4  2017-11-13   10.00
5  2017-11-18   31.00
6  2017-11-27   14.00
7  2017-11-29   10.00
8  2017-11-30   37.20
9  2017-12-16    8.00
10 2017-12-17   43.20
11 2017-12-17   49.60
12 2017-12-19  102.50
13 2017-12-19   28.80
14 2017-12-22   72.55
15 2017-12-23   24.80
16 2017-12-24   62.00
17 2017-12-26   12.40
18 2017-12-26   15.50
19 2017-12-26   40.00
20 2017-12-28   57.60
21 2017-12-31   37.20
22 2018-01-01   18.60
23 2018-01-02   12.40
24 2018-01-04   32.40
25 2018-01-05   17.00
26 2018-01-06   28.80
27 2018-01-11   20.80
28 2018-01-12   10.00
29 2018-01-12   26.00
我正在尝试绘制每月交易总额,这很好,但丑陋的x记号除外:

我想将其更改为月份和年份的名称,例如2019年1月。所以我对日期进行排序,使用strftime更改它们,然后再次绘制,但是日期的顺序完全混乱了

我用来对日期进行排序和转换的代码是:

transactions = transactions.sort_values(by='local_date')

transactions['month_year'] = transactions['local_date'].dt.strftime('%B %Y')

#And then groupby that column:

transactions.groupby('month_year').amount.sum().plot(kind='bar')
执行此操作时,月份和年份将配对在一起。2019年1月是2018年1月之后,等等

我原以为按日期排序可以解决这个问题,但事实并非如此。最好的方法是什么?

您可以通过将列转换为mont periods,然后在重命名中将PeriodIndex更改为自定义格式:

替代解决方案:

transactions = transactions.sort_values(by='local_date')
s = transactions.groupby(transactions['local_date'].dt.to_period('m')).amount.sum()
s.index = s.index.strftime('%B %Y')
s.plot(kind='bar')

您可以通过将列转换为mont periods,然后在重命名中将PeriodIndex更改为自定义格式:

替代解决方案:

transactions = transactions.sort_values(by='local_date')
s = transactions.groupby(transactions['local_date'].dt.to_period('m')).amount.sum()
s.index = s.index.strftime('%B %Y')
s.plot(kind='bar')