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

Pandas读取CSV后列索引异常:指定列报KeyError求助

Fixing KeyError When Reading Semicolon-Separated CSV in Pandas

It looks like your CSV file uses semicolons (;) as the delimiter instead of the default commas, which is why pandas is reading all your columns into a single combined string. Here's how to fix this:

1. Correctly Read the CSV with the Right Delimiter

The simplest and most straightforward fix is to specify the sep parameter in pd.read_csv() to tell pandas to use semicolons instead of commas:

import seaborn as sns
import pandas as pd
# Explicitly set semicolon as the delimiter
data = pd.read_csv("myfile.csv", sep=';')

After running this, check your columns again with data.columns—you should see separate column names like Index(['armonia', 'letra', 'interprete'], dtype='object') instead of the single merged string. Now your line newdata = data[["armonia","letra"]] will work without throwing a KeyError.

2. Alternative Fix: Split the Incorrectly Loaded Column

If you don't want to reload the file, you can split the single misread column into multiple proper columns using str.split():

# Split the combined column into separate columns
data = data['armonia;letra;interprete'].str.split(';', expand=True)
# Assign the correct column names
data.columns = ['armonia', 'letra', 'interprete']

This will break apart the single string column into three distinct columns with the names you need, letting you select the columns you want without issues.

Why This Happened

By default, pd.read_csv() uses commas (,) as the delimiter. Since your file uses semicolons to separate values, pandas couldn't tell where one column ends and the next begins—so it treated each entire row as a single value in one column. Specifying sep=';' gives pandas the right instruction to split your data properly.

内容的提问来源于stack exchange,提问作者Alejandro Marín

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:20:13