【问题标题】:Set time formatting on a datetime index when plotting Pandas Series绘制 Pandas 系列时在日期时间索引上设置时间格式
【发布时间】:2017-04-24 02:50:21
【问题描述】:

我有一个带有 DatetimeIndex 的 Pandas 数据框,频率为每月 (M)。但是,当我从此 Dataframe 中绘制一列时,即使这些位毫无意义,我的绘图上的标签也会显示日期和时间。我该如何解决这个问题,以便一个月只以YYYY-MM 格式显示?

【问题讨论】:

    标签: python pandas matplotlib timestamp


    【解决方案1】:

    在绘图之前对您的 DateTimeIndex 进行小修改,将它们转换为 PeriodIndex 并提供每月频率,就像这样 -

    a.index = a.index.to_period('M')  # Even a.index.astype('period[M]') works
    

    演示:

    考虑DF,如图所示:

    idx = pd.date_range('2016/1/1', periods=10, freq='M')
    df = pd.DataFrame(dict(count=np.random.randint(10,1000,10)), idx).rename_axis('start_date')
    df
    

    老DateTimeIndex:

    >>> df.index
    DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31', '2016-04-30',
                   '2016-05-31', '2016-06-30', '2016-07-31', '2016-08-31',
                   '2016-09-30', '2016-10-31'],
                  dtype='datetime64[ns]', name='start_date', freq='M')
    

    新PeriodIndex:

    >>> df.index = df.index.to_period('M')
    >>> df.index
    PeriodIndex(['2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06',
                 '2016-07', '2016-08', '2016-09', '2016-10'],
                dtype='period[M]', name='start_date', freq='M')
    

    绘制它们:

    df['count'].plot(kind='bar')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 2019-05-14
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      相关资源
      最近更新 更多