gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:30 28 4
gpt4 key购买 nike

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

picture of problem

最佳答案

通过将它们转换为 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

enter image description here

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

enter image description here

关于python - 绘制 Pandas 系列时在日期时间索引上设置时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41046630/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com