将pd.Grouper转换为plt.plot上的可读格式

时间:2019-05-15 12:31:29

标签: python pandas dataframe matplotlib

我正在使用Pandas和Matplotlib从SQL数据库绘制一些数据。

这是我的步骤:

  • 从数据库获取数据到pd.DataFrame
  • 使用Grouper('MS')将它们分组
  • 汇总以统计每个组中有多少项
  • 绘制图表
df = df.groupby(Grouper(key='published_at', freq='MS'))['id'].count()
ax = df.plot.bar(position=0.5, width=0.4, label="Items")

这就是我的情节:

enter image description here

我想将月份显示为“ 2019-04”,所以将其表示为“ Y-M”,但我不知道该怎么做。

由于我是Python的新手,因此不胜感激。谢谢!

2 个答案:

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

输出:

enter image description here

答案 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")