Python 在plt.plot上将pd.gropper转换为可读格式

Python 在plt.plot上将pd.gropper转换为可读格式,python,pandas,dataframe,matplotlib,Python,Pandas,Dataframe,Matplotlib,我正在使用Pandas和Matplotlib从SQL数据库中绘制一些数据 以下是我的步骤: 将数据库中的数据提取到pd.DataFrame中 使用Grouper('MS')对它们进行分组 聚合以计算每个组中有多少项 画图表 这就是我的情节: 我想把月份显示为“2019-04”,所以是“Y-M”,但我不知道怎么做 由于我对Python完全陌生,因此非常感谢您的帮助。谢谢大家! 以下内容适用于您的示例数据,但可能会因很多日期而失败: tmp_df = df.resample('MS',on='

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

以下是我的步骤:

  • 将数据库中的数据提取到pd.DataFrame中
  • 使用Grouper('MS')对它们进行分组
  • 聚合以计算每个组中有多少项
  • 画图表
这就是我的情节:

我想把月份显示为“2019-04”,所以是“Y-M”,但我不知道怎么做


由于我对Python完全陌生,因此非常感谢您的帮助。谢谢大家!

以下内容适用于您的示例数据,但可能会因很多日期而失败:

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()
输出:


似乎您只想重新格式化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")
试试这个
# 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")