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

读取CSV文件绘制堆叠柱线图时出现KeyError:['Cat1']不在索引中的问题排查求助

Fixing KeyError: ['Cat1'] not in index for Stacked Bar-Line Plot

Hey there, that KeyError you're hitting is super common when pandas doesn't parse your CSV columns the way you expect—even if you’re 100% sure Cat1 is right there in the file. Let’s break down the most likely fixes to get your plot working:

1. Your CSV uses spaces as separators (not commas)

By default, pd.read_csv() looks for commas to split columns, but your sample CSV uses spaces. That means pandas is probably reading the entire first row as one messy column name instead of splitting it into Cat1, Cat2, etc.

Fix this by telling pandas to use any number of spaces as the separator:

data = pd.read_csv("C:/Graphs/data.csv", sep=r'\s+')

First, confirm what columns pandas actually read with this quick check:

print(data.columns)

If the output is a single string instead of separate column names, this separator fix will solve the KeyError.

2. Hidden spaces or weird characters in column names

Sometimes column names have invisible leading/trailing spaces (like Cat1 or Cat1 ) that you can’t spot at a glance. Clean up all column names with one line:

data.columns = data.columns.str.strip()

This removes any extra whitespace from the start/end of every column name.

3. Double-check you’re reading the right file

It sounds silly, but it’s easy to accidentally point to an old version of data.csv in another folder. Verify the content you’re loading with:

print(data.head())

Make sure the output matches the sample CSV you shared.

4. Fix undefined variables in your code

You’re using width and colors but haven’t defined them—this will throw another error once you fix the KeyError. Add these lines before plotting:

width = 0.8  # Adjust to your preferred bar width
colors = ['#1f77b4', '#ff7f0e', '#2ca02c']  # Example color palette

Full Modified Code

Here’s the complete working version with all fixes applied:

import pandas as pd
import matplotlib.pyplot as plt

xtick = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]

# Read CSV with correct separator and clean column names
data = pd.read_csv("C:/Graphs/data.csv", sep=r'\s+')
data.columns = data.columns.str.strip()

# Define missing plot variables
width = 0.8
colors = ['#1f77b4', '#ff7f0e', '#2ca02c']

# Plot stacked bar chart
data[['Cat1','Cat2','Cat3']].plot(kind='bar', width=width, stacked=True, color=colors, figsize=(6.5, 3))
plt.ylabel("Latency (ms)")
plt.ylim(0, 75000)

# Plot secondary line chart
data['Output_data'].plot(secondary_y=True, color='darkslategrey', marker='o', markersize=2)
plt.xlim([-width, len(data['Cat3']) - width])
plt.ylim(0, 6)
plt.ylabel("Output-data")

# Display the final plot
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 07:49:09