Pivot Table列索引异常:无法选取列绘制Matplotlib柱状图
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
.columnsoutput only shows['ship_id'] .shapereturns(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

