Python中出现KeyError报错求助:Y = df['people'].values行报错原因
Hey there, let's break down why you're getting that frustrating KeyError when trying to access df['people'] and how to fix it.
常见原因及解决方法
列名拼写或大小写不匹配
It's super easy to mistype a column name—maybe your CSV usesPeople(capital P),people_count, or another variation instead ofpeople. First, let's confirm exactly what columns are in your DataFrame:print("List of columns in your DataFrame:", df.columns.tolist())Match the output with the name you're trying to use, and adjust
df['people']to the correct column name if needed.列名存在多余空格或特殊字符
Sometimes CSV exports add hidden spaces before/after column names (like' people 'instead of'people'). You can clean up all column names to remove these:df.columns = df.columns.str.strip() # Removes leading/trailing whitespaceThen try accessing
df['people']again.CSV分隔符不正确
By default,pd.read_csvuses commas as separators, but if your CSV uses tabs (\t), semicolons (;), or something else, pandas might lump all data into a single column. Fix this by specifying the correct separator:df = pd.read_csv("project.csv", sep="\t") # Use sep=";" if your file uses semicolons文件路径错误或CSV损坏
Double-check that you're reading the right file. Run this to see your current working directory and confirmproject.csvis there:import os print("Current working directory:", os.getcwd())If the file isn't in this folder, use the full path (like
pd.read_csv("/Users/you/Documents/project.csv")) or move the file to your working directory.
修改后的示例代码
Here's how you can adjust your code to debug and fix the issue:
import matplotlib.pyplot as plt from sklearn import linear_model import pandas as pd import os # Verify current working directory print("Current working directory:", os.getcwd()) df = pd.read_csv("project.csv") # Print all columns to check for matches print("Available columns:", df.columns.tolist()) # Clean up column names df.columns = df.columns.str.strip() print(df.shape) df.head() X = df['day'].values Y = df['people'].values # This should work now if we fixed the column issue
内容的提问来源于stack exchange,提问作者hammer

