我正在使用Pandas和Matplotlib从SQL数据库绘制一些数据。
这是我的步骤:
df = df.groupby(Grouper(key='published_at', freq='MS'))['id'].count()
ax = df.plot.bar(position=0.5, width=0.4, label="Items")
这就是我的情节:
我想将月份显示为“ 2019-04”,所以将其表示为“ Y-M”,但我不知道该怎么做。
由于我是Python的新手,因此不胜感激。谢谢!
答案 0 :(得分:1)
以下内容适用于您的示例数据,但是可能会因为很多日期而失败:
tmp_df = df.resample('MS',on='published_at').id.count()
plt.figure(figsize=(10,6))
plt.bar(tmp_df.index.strftime("%Y-%m"), tmp_df)
plt.show()
输出:
答案 1 :(得分:0)
似乎您只想重新格式化datetime列。
如果您不是从第2行开始,那么看起来您已经以正确的格式转换了此列,否则从第5行开始了。
# Convert to datetime
df['published_at'] = pd.to_datetime(df['published_at'])
# You can start from here, if you have already converted your column
df['published_at_YM'] = df['DOB'].dt.strftime('%Y-%m')
df = df.groupby(Grouper(key='published_at_YM', freq='MS'))['id'].count()
ax = df.plot.bar(position=0.5, width=0.4, label="Items")