【问题标题】:How to plot Month name in correct order, using strftime?如何使用 strftime 以正确的顺序绘制月份名称?
【发布时间】:2020-02-15 10:59:47
【问题描述】:

这是我的数据框的快速浏览:

   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-ticks:

我想将其更改为月份和年份的名称(例如 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')

执行此操作时,Month_year 将配对在一起。 2019 年 1 月在 2018 年 1 月等之后。

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

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以通过Series.dt.to_period 将列转换为蒙特周期,然后将PeriodIndex 更改为rename 中的自定义格式:

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

    替代解决方案:

    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')
    

    【讨论】:

      猜你喜欢
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多