绘制 Pandas 系列时设置日期时间索引的时间格式

hel*_*loB 2 python timestamp matplotlib pandas

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

问题图片

Nic*_*eli 5

在绘制之前对您进行一些小修改DateTimeIndex,将它们转换为PeriodIndex并提供每月频率,如下所示 -

a.index = a.index.to_period('M')  # Even a.index.astype('period[M]') works
Run Code Online (Sandbox Code Playgroud)

演示:

考虑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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

老的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')
Run Code Online (Sandbox Code Playgroud)

新的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')
Run Code Online (Sandbox Code Playgroud)

绘制它们:

df['count'].plot(kind='bar')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述