Skip to main content
 首页 » 编程设计

python之绘制 Pandas 系列时在日期时间索引上设置时间格式

2024年10月17日8oomusou

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

请您参考如下方法:

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

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