Pandas读取CSV后列索引异常:指定列报KeyError求助
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

