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

Python代码报错KeyError: 'date',CSV日期格式为yyyy-mm-dd求解决

KeyError: 'date' 问题排查与解决

错误根源

你执行了df.set_index('date', inplace=True),这一步已经将CSV中的date列设置为DataFrame的索引,原date列会被从普通列中移除,后续再通过df['date']访问自然会触发KeyError。

修复方案

方案1:直接从索引获取日期数据

既然date已经是索引,直接访问索引即可完成需求:

import pandas as pd
import numpy as np

df = pd.read_csv('data.csv')
df.set_index('date', inplace=True)

x = np.array(df['subscribersGained'].dropna().values, dtype=float)
# 直接处理索引,无需按列名查找
y = np.array(pd.to_datetime(df.index.dropna()).astype(float))

方案2:保留date列同时设置为索引

如果需要同时保留date列和将其作为索引,在set_index时添加drop=False参数:

import pandas as pd
import numpy as np

df = pd.read_csv('data.csv')
# 设置索引但保留原date列
df.set_index('date', inplace=True, drop=False)

x = np.array(df['subscribersGained'].dropna().values, dtype=float)
# 此时df['date']可正常访问
y = np.array(pd.to_datetime(df['date'].dropna()).astype(float))

额外优化

  • 代码中重复读取了两次data.csv到df和data,若data变量未被使用,建议删除该语句以避免冗余IO操作。
  • pd.to_datetime处理完成后,直接用.astype(float)转换即可,无需额外调用.index.values,可简化代码逻辑。

内容的提问来源于stack exchange,提问作者Benjamin McDowell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:50:31