You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataFrame分组绘图需求及groupby操作AttributeError问题求助

问题根源与解决方案

错误原因

出现AttributeError: 'AxesSubplot' object has no attribute 'groupby'的核心问题是:你之前可能执行过类似df = df.plot(...)的代码,把绘图返回的Matplotlib轴对象(AxesSubplot)赋值给了df,导致原本的DataFrame被覆盖,后续调用groupby自然会出错。

解决步骤

1. 恢复原始DataFrame

重新获取或定义你的原始数据框,确保df指向的是真正的DataFrame:

import pandas as pd

# 手动重建示例数据(如果是从文件读取,重新执行读取代码即可)
data = {
    'Year': [1111, 2222, 3333],
    'Month': ['JAN', 'feb', 'mAR'],
    'Product': ['A', 'B', 'C'],
    'startTime': ['11 PM', '6 AM', '4 PM'],
    'Endtime': ['12 am', '6.30 PM', '4.30 PM']
}
df = pd.DataFrame(data)

2. 修正分组逻辑

原代码里的dates.dt.year无对应列,且Product是字符串类型,用sum无意义,建议用count统计数量。以下是几种分组场景的正确代码:

  • 按Year分组:
    grouped_year = df.groupby('Year').agg(overall=('Product', 'count'))
    
  • 按Month分组(先统一月份大小写,避免分组重复):
    df['Month'] = df['Month'].str.upper()
    grouped_month = df.groupby('Month').agg(overall=('Product', 'count'))
    
  • 按Product分组:
    grouped_product = df.groupby('Product').agg(overall=('Year', 'count'))
    

3. 正确绘制图表

绘图时不要把结果赋值给原始df,避免覆盖数据框:

import matplotlib.pyplot as plt

# 绘制按Year分组的柱状图
grouped_year.plot(kind='bar', title='Products by Year')
plt.xlabel('Year')
plt.ylabel('Product Count')
plt.show()

# 或者直接用Matplotlib绘制按Month分组的图表
plt.bar(grouped_month.index, grouped_month['overall'])
plt.title('Products by Month')
plt.xlabel('Month')
plt.ylabel('Product Count')
plt.show()

内容的提问来源于stack exchange,提问作者SHYLAJA NANDHINI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:55:24