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

使用Python .pivot_table处理CSV时遭遇KeyError问题求助

Fixing KeyError in pandas pivot_table

Hey there, that KeyError you're hitting almost always boils down to one simple issue: one or more of the column names you specified in your pivot_table call don't exist in your DataFrame (or there's a spelling/casing/format mismatch). Let's walk through how to diagnose and fix this step by step.

Step 1: Verify Your Column Names First

First, let's confirm exactly what columns are present in your training_tracker DataFrame. Run this code to print out all column names clearly:

print("Available columns:", training_tracker.columns.tolist())

Compare the output to the column names you used in your pivot_table:

  • POD, Name, Date Start, Date Finish, Total Days, Training Status, Exam Needed
  • Training
  • DemoA

Look for any discrepancies:

  • Did you mix up uppercase/lowercase? (e.g., training instead of Training)
  • Are there hidden spaces in column names? (e.g., Demo A instead of DemoA)
  • Did you misspell any name? (e.g., Exam Needed vs Exam Requried)

Step 2: Fix Column Name Mismatches

If you spot a mismatch, adjust your pivot_table code to use the exact column name from your DataFrame. For example, if your CSV has Demo A (with a space) instead of DemoA, update your code like this:

pivot_test = training_tracker.pivot_table(
    index=['POD', 'Name', 'Date Start', 'Date Finish', 'Total Days', 'Training Status', 'Exam Needed'],
    columns='Training',
    values='Demo A'  # Fixed column name here
)

Step 3: Clean Column Names (Optional but Helpful)

If your CSV has messy column names (extra spaces, inconsistent casing), you can standardize them first to avoid future issues:

# Strip extra spaces from column names and convert to lowercase
training_tracker.columns = training_tracker.columns.str.strip().str.lower()

# Now use lowercase column names in your pivot_table
pivot_test = training_tracker.pivot_table(
    index=['pod', 'name', 'date start', 'date finish', 'total days', 'training status', 'exam needed'],
    columns='training',
    values='demoa'
)

Step 4: Double-Check for Edge Cases

If you've confirmed all column names are correct and still get the error, check if:

  • The column exists but is empty (unlikely to cause KeyError, but worth verifying with training_tracker['DemoA'].head())
  • You accidentally loaded the wrong CSV file (confirm the file path 'Training Tracker_v02.csv' points to the correct file)

That should resolve the KeyError—most pivot_table KeyErrors are just simple column name typos or formatting issues!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:39:40