【问题标题】:Convert pd.Grouper to human-readable format on plt.plot在 plt.plot 上将 pd.Grouper 转换为人类可读的格式
【发布时间】:2019-05-15 20:57:03
【问题描述】:

我正在使用 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")

这就是我的情节:

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

由于我是 Python 的新手,任何帮助将不胜感激。谢谢!

【问题讨论】:

标签: python pandas dataframe matplotlib


【解决方案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()

输出:

【讨论】:

    【解决方案2】:

    您似乎只想重新格式化日期时间列。

    看起来您已经将该列转换为正确的格式,如果不是从第 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2021-06-21
      • 2010-12-11
      • 1970-01-01
      • 2018-04-22
      • 2017-06-07
      • 2012-12-02
      相关资源
      最近更新 更多