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

Python中出现KeyError报错求助:Y = df['people'].values行报错原因

解决Pandas中KeyError: 'people'的问题

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 uses People (capital P), people_count, or another variation instead of people. 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 whitespace
    

    Then try accessing df['people'] again.

  • CSV分隔符不正确
    By default, pd.read_csv uses 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 confirm project.csv is 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:38:07