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

Pivot Table列索引异常:无法选取列绘制Matplotlib柱状图

Fixing KeyError When Accessing Pivot Table Column for Matplotlib Bar Chart

Hey there, let's break down why you're running into that KeyError and how to fix it quickly!

The Root Cause

When you created your pivot table, you set hours_diff_last_ais_and_last_processed_grouped as the index parameter. This tells pandas to turn that column into the row index of the pivot table, not a regular data column. That's why:

  • Your .columns output only shows ['ship_id']
  • .shape returns (45,1) (only 1 data column exists)
  • Trying to call HoursDiffLastAisProcessPivotTable["hours_diff_last_ais_and_last_processed_grouped"] throws a KeyError—it's not in the columns anymore!

Two Easy Fixes

1. Convert the Index Back to a Regular Column

If you want that grouped hours column to behave like a standard data column, add .reset_index() when creating your pivot table:

HoursDiffLastAisProcessPivotTable = pd.pivot_table(
    df,
    index=["hours_diff_last_ais_and_last_processed_grouped"],
    values=['ship_id'],
    aggfunc='count',
    fill_value=''
).reset_index()

After this change, running print(HoursDiffLastAisProcessPivotTable.columns) will show both columns, and your original code to assign x will work perfectly:

x = HoursDiffLastAisProcessPivotTable["hours_diff_last_ais_and_last_processed_grouped"]

2. Directly Access the Index (Keep Pivot Table Structure)

If you prefer to keep the pivot table's original structure with the grouped hours as the index, just fetch the index directly for your x-axis data:

x = HoursDiffLastAisProcessPivotTable.index

You can then plot your bar chart like this:

plt.bar(x, HoursDiffLastAisProcessPivotTable['ship_id'])
plt.xlabel('Hours Since Last AIS & Processed (Grouped)')
plt.ylabel('Number of Ships')
plt.title('Ship Count by Hours Difference Group')
plt.show()

Either approach will let you access the data you need to build your Matplotlib bar chart.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:32:54