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

使用Pandas读取CSV指定列报错:KeyError: 'centroid'求助

Fixing the KeyError: 'centroid' in Your Pandas Code

Hey there, let's work through this KeyError issue together! The error means Pandas can't find a column named centroid in your DataFrame, so let's break down the most likely fixes step by step:

1. First, Check What Columns Pandas Actually Sees

Before guessing at fixes, let's confirm exactly what columns Pandas is parsing from your CSV. Modify your code to print the column names first:

import pandas as pd
df = pd.read_csv('data/hasil_cluster.csv', encoding="ISO-8859-1")
print("Available columns:", df.columns)

This will show you the raw column names Pandas detected—sometimes there are hidden spaces, special characters, or the file uses a different separator than you expect.

2. Fix the CSV Separator (Most Common Culprit)

Looking at your example CSV format, you used semicolons (;) to separate individual rows (like word,centroid;she,1;great,0). If your actual CSV file uses semicolons as the column separator instead of commas, Pandas will read the entire row as a single column, hence the KeyError.

Update your read_csv call to specify the correct separator:

df = pd.read_csv('data/hasil_cluster.csv', encoding="ISO-8859-1", sep=';')

If the separator is a tab instead, use sep='\t' instead.

3. Clean Up Hidden Whitespace in Column Names

Sometimes column names have extra spaces or invisible characters you can't spot at a glance (like a trailing space after centroid). Clean up all column names by stripping whitespace:

df.columns = df.columns.str.strip()
print(df['centroid'])

4. Verify the Raw CSV Content

If the above steps don't work, let's check the actual content of your CSV file to make sure the column name is exactly centroid. Run this code to print the first few lines:

with open('data/hasil_cluster.csv', 'r', encoding="ISO-8859-1") as f:
    print("First 5 lines of the CSV:")
    for line in f.readlines()[:5]:
        print(repr(line))  # Shows hidden characters like spaces or weird newlines

This will reveal typos, special characters, or formatting issues that might be throwing Pandas off.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:17:49